标签:
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example:
Given num = 16, return true. Given num = 5, return false.
Follow up: Could you solve it without loops/recursion?
Solution:
1 bool isPowerOfFour(int num) 2 { 3 while (num >= 4) 4 { 5 if ((num & 0x03) != 0) 6 return false; 7 num >>= 2; 8 } 9 10 return num == 1; 11 }
a) num & (num - 1)可以用来判断一个数是否为2的次方数
b) 通过与0x55555555与运算
1 bool isPowerOfFour(int num) 2 { 3 return num > 0 && !(num & (num - 1)) && (num & 0x55555555) == num; 4 }
标签:
原文地址:http://www.cnblogs.com/ym65536/p/5573882.html