【剑指offer】二进制中1的个数(java)

版权声明:转载请注明出处 https://blog.csdn.net/fan_lulu/article/details/84314187

问题描述:输入一个二进制数,我们记为num,计算出num中有几个1,结果用count存储

思路分析:如二进制数11011,将其减1,得11010,再与原来的数做与运算 11011&11010,得11010,此二进制数相比原二进制数,数中的1少了一个。重复此过程,直至该数变为0,则结束循环。

java代码实现:

/**
 * Created by Administrator on 2018/11/21.
 */
public class Solution {
    public static int NumberOf1(int n) {
        int count=0;
        while(n!=0){
            int n_=n-1;
            n=n&n_;
            count++;
        }
        return count;
    }
    public static void main(String args[]){
        int n=17;
       System.out.println(NumberOf1(n));
    }
}

输出结果:

猜你喜欢

转载自blog.csdn.net/fan_lulu/article/details/84314187