Number of 1 Bits / Power of Two(LeetCode)

统计无符号整数二进制中1的个数:

class Solution {
public:
	int hammingWeight(uint32_t n) {
		int bit,num=0;
		while(n>0){
			bit=n%2;
			n=n>>1;
			if(bit)
				num++;
		}
		return num;
	}
};

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

Example 1:

Input: 1
Output: true

Example 2:

Input: 16
Output: true

Example 3:

Input: 218
Output: false

判断一个数是不是2的次幂。

思路:

主要是利用2的整数幂的二进制只有最高位是1,然后仿照进制转化的方式,判断就行了。1是2的0次幂。

class Solution {
public:
	bool isPowerOfTwo(int n) {
		if(n<=0) return false;
		//2的整数幂的二进制只有最高位是1
		int bit;
		while(n>1){
			bit=n%2;
			n=n>>1;
			if(bit)
				return false;
		}
		return true;
	}
};


猜你喜欢

转载自blog.csdn.net/u014485485/article/details/80339097
今日推荐