位运算、递归————4的幂

方法一:递归

 1 class Solution {
 2 public:
 3     bool isPowerOfFour(int num) {
 4         if(num<=0) return false;
 5         if(num==1) return true;
 6         if(num%4 == 0){
 7             return isPowerOfFour(num/4);
 8         }
 9         else return false;
10     }
11 };

方法二、位运算

若一个数为4的幂,则1出现在奇数位(例如:01010101010101010101010101010101),那么满足

  • 与10101010(偶数为1,奇数为0)的32位的二进制整数相与为0
    • 010101010101010......& 1010101010101010101010...(负数) == 0
    • 010101010101010...... & 0010101010101010.....(正数) == 0
  • 且1的个数为1,则说明是4的幂次
1 class Solution {
2 public:
3     bool isPowerOfFour(int num) {
4         bitset<32> a=num;
5         return !(num&2863311530)&&a.count()==1;
6     }
7 };
原文地址:https://www.cnblogs.com/pacino12134/p/11051522.html