第一次在leetcode上刷题,居然会紧张。。。其实这道题去年8月份就在《编程之美》上遇到过,当时自己用的对2求余数的方法,答案提供了一个移位的方法,也都做过笔记,没想到隔了半年再练手的时候这么生疏,明明知道大概是个怎样的思路,但是一敲出来就各种错误,也是醉了。所以说,算法题只是做过是没用的,做过两三遍也是没用的,关键是能做到每一次做都能快速并且准确无误地做出来。
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.
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int temp = 0;
int count = 0;
for (int i = 0; i < 32; i ++){
temp = n >> i;
temp &= 0x01;
if (temp != 0)
count ++;
}
return count;
}
}
下面是leetcode里vote最多的一个解题方法,大概思路也差不多,就是少用了一个变量,而且用到了>>>运算符,说实话在这之前我都不知道这个符号的意思,我单纯地想着把n>>>=1替换成n = n >>1效果也一样,但是运行之后会提示"Time Limit Exceeded"错误,后来查过才知道原来>>>是无符号右移的意思,涨姿势了。
</pre><pre name="code" class="java">public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int result = 0;
while (n != 0) {
if ((n & 1) == 1) {
result++;
}
n >>>= 1;
}
return result;
}
}