在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given an integer (signed 32 bits), write a function to check whether it is a power of 4. Example 1: Input: 16
Output: true
Example 2: Input: 5
Output: false
Follow up: Could you solve it without loops/recursion? 给定一个整数 (32 位有符号整数),请编写一个函数来判断它是否是 4 的幂次方。 示例 1: 输入: 16 输出: true 示例 2: 输入: 5 输出: false 进阶: 20ms 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 }
|
请发表评论