Number of 1 Bits
给个整数, 数一. 因为是Integer,所以一共32位. 1 << i 就是每个位上的1.
1 2 3 4 5 6 7 8 9 10 11 |
public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { int res = 0; for(int i = 0 ; i < 32; i++) { if((n & (1 << i)) != 0) res++; } return res; } } |