标签:
这道题考察的是一个二进制的特性。通过n&(n-1)可以判断n的二进制表示中有几个1.(最开始超时这道题的时候我心中是万马奔腾的)
// you need to treat n as an unsigned value
public int hammingWeight(int n) { int count=0;while(n!=0) { count++; n = n & (n - 1); } return count; }
开始我的代码:
public int hammingWeight(int n) { int count=0; while(n!=0) { count+=n&0x1; n=n>>1; } return count; }
LeetCode-191. Number of 1 Bits
标签:
原文地址:http://www.cnblogs.com/ren-jie/p/5298145.html