判定一个数是否为2的幂,方法很多
方法一:位操作
若n为2的幂,必有n&(n-1)==0
1 static int wing=[]() 2 { 3 std::ios::sync_with_stdio(false); 4 cin.tie(NULL); 5 return 0; 6 }(); 7 8 class Solution 9 { 10 public: 11 bool isPowerOfTwo(int n) 12 { 13 return n>0&&((n&(n-1))==0); 14 } 15 };
方法二:可以用迭代余除的方法
1 if(n==0) return false; 2 while(n%2==0) n/=2; 3 return (n==1);
方法三:递归,本质还是余除
1 return n>0 && (n==1 || (n%2==0 && isPowerOfTwo(n/2)));
方法四:int类型中,2的最大幂为1073741824
所以,有如下判定方法:
1 return n>0 && (1073741824 % n == 0);
浙公网安备 33010602011771号