关闭

Number of 1 Bits

标签: Bit Manipulation
130人阅读 评论(0) 收藏 举报
分类:
public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int count = 0;
        for (int i = 1; i < 33; i++) {
            if ((n & 1) != 0) {
                count++;
            }
            n = n >> 1;
        }
        return count;
    }
}


public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int count = 0;
        while (n != 0) {
            n = n & (n - 1);
            count++;
        }
        return count;
    }
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:27704次
    • 积分:2365
    • 等级:
    • 排名:第16334名
    • 原创:214篇
    • 转载:2篇
    • 译文:0篇
    • 评论:0条