【剑指 Offer 】15. 二进制中1的个数

    科技2022-07-20  129

    题目:15. 二进制中1的个数

    思路1: 本题可以判断n的最后一位是否为1,来计算1的个数,采用逻辑右移的方式。 (对算术右移和逻辑右移分不清的可以看这篇文章)。

    代码:

    public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { int sum = 0; while(n!=0){ sum += (n&1); n = n>>>1;//无符号右移 } return sum; } }

    思路2: 下面介绍一个运算更快的方法,原理就是以下这句话:

    x & (x -1 )的结果表示去掉x中最右边的1之后的数。

    代码

    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-1); count ++; } return count; } }
    Processed: 0.010, SQL: 8