13.剑指Offer-二进制中 1 的个数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cuicanxingchen123456/article/details/88689938

题目描述

输入一个整数,输出该数二进制表示中 1 的个数。

方法一:

n&(n-1)

该位运算去除 n 的位级表示中最低的那一位。

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

时间复杂度:O(M),其中 M 表示 1 的个数。

public int NumberOf1(int n) {
    int cnt = 0;
    while (n != 0) {
        cnt++;
        n &= (n - 1);
    }
    return cnt;
}

方法二:

Integer.bitCount()

public int NumberOf1(int n) {
    return Integer.bitCount(n);
}

 

方法三

public class Binaryof1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc=new Scanner(System.in);
		int n=sc.nextInt();
		String str=Integer.toBinaryString(n);
		String[] sstr=str.split("");
		String a="";
		int num=0;
		for(int i=0;i<sstr.length;i++){
			System.out.println(sstr[i]);
			if(sstr[i].equals("1")){
				num++;
			}
		}
		System.out.println(num);
	}

}

猜你喜欢

转载自blog.csdn.net/cuicanxingchen123456/article/details/88689938
今日推荐