标签:
Given an integer, write a function to determine if it is a power of two.
Tags: Math Bit Manipulation
Similar Problems: (E) Number of 1 Bits (E) Power of Three (E) Power of Four
该题判断某个给定的整数是否为2的次方数?
首先,观察下2的次方数的二进制写法的特点:
可知,若某数是2的次方数,则其对应的二进数的最高位必然是1,且其它位均为0。
思路1:
1 class Solution { 2 public: 3 bool isPowerOfTwo(int n){ 4 if (n<=0) 5 { 6 return false; 7 } 8 return (n & (n-1)) == 0; 9 } 10 };
思路2:
1 class Solution { 2 public: 3 bool isPowerOfTwo(int n) { 4 int count = 0; 5 while (n > 0) 6 { 7 count += (n & 1); 8 n >>= 1; 9 } 10 return count == 1; 11 } 12 };
标签:
原文地址:http://www.cnblogs.com/whl2012/p/5665263.html