★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(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 }