《剑指offer》11.二进制中1的个数

题目地址:https://www.nowcoder.com/practice/8ee967e43c2c4ec193b040ea7fbb10b8?tpId=13&tqId=11164&rp=4&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

解题思路:最直接的想法是,每次将数字右移一位,判断是否为1,是的话个数加一,否则继续右移,知道数字为0。相同的思路是,n&(n-1)的结果就是将n最右边不为0的数变成0,例如

                                                               n : 10110100
                                                               n-1 : 10110011
                                                               n&(n-1) : 10110000

所以重复上述这种运算直到n为0停止循环。时间复杂度为O(logM),其中M是1的个数。

public class Solution {
    public int NumberOf1(int n) {
        if(n==0)
            return 0;
        int count = 0;
        while(n!=0){
            n = n&(n-1);
            count++;
        }
        return count;
    }
}


 

猜你喜欢

转载自blog.csdn.net/qq_28900249/article/details/89295154