Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011
, so the function should return 3.
题意:找一个无符号整数中1的位数。
基本思路:
1. 先说最复杂也最好理解的方法。把无符号整数变成它的二进制形式,然后变成一个字符串,去查字符串的每一位是否为1,如果是结果自增一次,最后返回结果。
这个数只有32位,即使用这种方法所消耗的时间也不会很长。(貌似python提交的结果大部分都是这种),优点在于符合人类习惯,易于理解。缺点就是慢使用过多空间。
代码如下:(用c或者c++写这种转字符串的要写很长所以直接用了Python)
1 class Solution(object): 2 def hammingWeight(self, n): 3 return bin(n).count("1");
2. 稍微抽象点的思路就是,按位与&,一个数去和32 个不同位上为1其他位为0的数进行与运算,如果不为0说明某一位为1,否则为0.
举例 0000 0000 0000 0000 0000 0000 0000 1110 与 1000进行与运算只会得到 1000 即后数第四位为 1, 依次类推。
代码如下:
1 int hammingWeight(uint32_t n) { 2 int cnt = 0; 3 for(int i=0;i<32;i++) 4 if(n&(1<<i)) 5 cnt++; 6 return cnt; 7 }
3. 还有一种更抽象的思路:一个数有n-1个1和1个1。
直接写代码:
1 int hammingWeight(uint32_t n) { 2 int cnt = 0; 3 while(n) 4 { 5 n &= (n-1); 6 ++cnt; 7 } 8 return cnt; 9 }
运行时间上第3种思路和第2种相差不多,但是每一个都比第一种快很多。