[Swift]LeetCode342. 4的幂 | Power of Four

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-mqvbemtt-hh.html 
➤若是连接不是山青咏芝的博客园地址,则多是爬取做者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持做者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Given an integer (signed 32 bits), write a function to check whether it is a power of 4.git

Example 1:github

Input: 16
Output: true 

Example 2:微信

Input: 5
Output: false

Follow up: Could you solve it without loops/recursion?函数

给定一个整数 (32 位有符号整数),请编写一个函数来判断它是不是 4 的幂次方。oop

示例 1:spa

输入: 16
输出: true

示例 2:code

输入: 5
输出: false

进阶:
你能不使用循环或者递归来完成本题吗?htm


20msblog

1 class Solution {    
2     func isPowerOfFour(_ num: Int) -> Bool {
3         return num > 0 && (num & (num-1)) == 0 
4                    && (num & 0xAAAAAAAA) == 0;
5     }      
6 }

20ms

 1 class Solution {
 2     func isPowerOfFour(_ num: Int) -> Bool {
 3         if num <= 0 {
 4             return false
 5         }
 6         
 7         if num == 1 {
 8             return true
 9         }
10         
11         if num % 4 == 0 {
12             return self.isPowerOfFour(num / 4)
13         } else {
14                    
15             return false
16         }
17         
18     }
19 }

24ms

 1 class Solution {
 2     func isPowerOfFour(_ num: Int) -> Bool {
 3         guard num > 0 else {
 4             return false
 5         }
 6         
 7         if num & (num - 1) == 0 && (num & 0x55555555) != 0{
 8             return true
 9         }
10         return false
11     }
12 }

 

28ms

 1 class Solution {
 2     func isPowerOfFour(_ num: Int) -> Bool {
 3         var mod:Int = 0
 4         var number:Int = num
 5         while(mod == 0 && number >= 4)
 6         {
 7             mod = number % 4
 8             number /= 4
 9         }
10         if mod != 0 
11         {
12             return false
13         }
14         if number == 1
15         {
16             return true
17         }
18         return false
19     }
20 }
相关文章
相关标签/搜索