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.
1 class Solution { 2 public: 3 bool isPowerOfTwo(int n) { 4 if (n == 0) 5 return false; 6 while (n != 1) 7 { 8 if (n % 2 != 0) 9 break; 10 else 11 { 12 n = n / 2; 13 } 14 } 15 if (n == 1) 16 return true; 17 else 18 return false; 19 } 20 };
1 class Solution { 2 public: 3 bool isPowerOfTwo(int n) { 4 bitset<64> bs(n); 5 if(bs.count()==1) 6 return true; 7 else 8 return false; 9 } 10 };