variable precision SWAR算法

二进制中1的个数

http://www.nowcoder.com/questionTerminal/8ee967e43c2c4ec193b040ea7fbb10b8

经典Redis中BITCOUNT命令的算法

原理可以看这篇博客

variable precision SWAR算法

public class JZ11 {
    public int NumberOf1(int n) {
        n = (n & 0x55555555) + ((n >> 1) & 0x55555555);
        n = (n & 0x33333333) + ((n >> 2) & 0x33333333);
        n = (n & 0x0F0F0F0F) + ((n >> 4) & 0x0F0F0F0F);
        n = ((n * 0x01010101) >> 24);
        return n;
    }

    @Test
    public void Test() {
        Assert.assertEquals(NumberOf1(10), 2);
        Assert.assertEquals(NumberOf1(0),0);
        Assert.assertEquals(NumberOf1(Integer.MAX_VALUE), 31);
        Assert.assertEquals(NumberOf1(Integer.MIN_VALUE), 1);
        Assert.assertEquals(NumberOf1(-1),32);
    }
}
全部评论

相关推荐

06-27 18:45
中山大学 Ruby
25届应届毕业生,来广州2个礼拜了,找不到工作,绝望了,太难过了…
应届想染班味:9爷找不到工作只能说明,太摆了或者太挑了。
点赞 评论 收藏
分享
05-09 14:45
门头沟学院 Java
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-27 20:55
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务