Leetcode刷题笔记题解(C++):231. 2的幂

tech2022-08-05  127

思路1:常规做法,一直除以2直到1为止

思路2:2的幂在二进制表示只有1个1,则对位1的个数进行判断即可

代码如下:

class Solution { public: //常规做法,一直除下去 bool isPowerOfTwo1(int n) { if(n==1) return true; if(n<=0||n%2==1) return false; while(n%2==0){ n=n/2; if(n==1) return true; } return false; } //位1的个数为1则符合,否则则不是 bool isPowerOfTwo(int n) { if(n==1) return true; if(n<=0||n%2==1) return false; return !(n&(n-1)); } };

 

最新回复(0)