leetcode Power of Two

Given an integer, write a function to determine if it is a power of two.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

 
这道题想明白以后是非常简单的,首先不可以用连除,时间浪费太多,肯定time超时;
其实,2的幂次方转换成2进制后,就是二进制位只有一个1,永远只能有一个1,2的0次方,2的1次方,2的2次方等等````
但是,二进制后1的个数统计我不会。。。。因为右移这边我不太会。。因而我去百度了一下统计1个数的程序。。
1 int findone(unsigned int n)
2 { 
3     for(int i=0;n>0;n>>=1) 
4          i+=(n&1); //是按位与,一位一位的和1与,因此我们需要每次右移一位来判断最右边的那个是不是1
5     return i; 
6 } 

附代码:

 1 class Solution {
 2 public:
 3     bool isPowerOfTwo(int n) {
 4     int i;
 5     for(i=0;n>0;n>>=1) 
 6          i+=(n&1); 
 7     if(i==1) return true;
 8     else return false;
 9         
10     }
11 };
原文地址:https://www.cnblogs.com/LUO77/p/4986899.html