191. Number of 1 Bits
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;
要不要那么简单,我用了二进制的直接转换:
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
String s = Integer.toBinaryString(n);//将数字转换为二进制字符串,呵呵
int num =0;
for(int i = 0; i< s.length(); i++){
if(s.charAt(i)!=0) num++;
}
return num;
}
}
so easy ……