Count the number of 1s in a binary number

package test24;
import java.util.Scanner;
public class Tesk {
    
    
public static void main(String[] args) {
    
    
    System.out.println("请输入一个数: ");
    Scanner input = new Scanner(System.in);
    int num = input.nextInt();
    int count = 0;
    for(int i = 0;i < 32;i++){
    
    
        if(((num>>i) & 1) == 1){
    
    
            count ++;
        }
    }
    System.out.println("1的个数是:"+count);
}
}

The above code can calculate the correct result, but when the number of inputs is small , it does many useless calculations, and the efficiency is too low, so we make the following improvements:
Insert picture description here
each time we let n & n-1 , the number of AND is 1. Number of

package test24;
import java.util.Scanner;
public class Tesk {
    
    
public static void main(String[] args) {
    
    
    System.out.println("请输入一个数: ");
    Scanner input = new Scanner(System.in);
    int num = input.nextInt();
    int count = 0;
    while(num != 0){
    
    
            count++;
            num = num & (num - 1);
        }
        System.out.println("该数的二进制中共有"+count+"个1");
    }
}

Result display:
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_45658339/article/details/108807671