Ideas:
- Since the int type occupies 4 bytes, the for loop performs 32 times
- num right shift and 1 phase and
Code:
import java.util.Scanner;
public class pra1214 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("请输入一个整数:");
int num=sc.nextInt();
int count=0;
for(int i=0;i<32;i++){
if((1&(num>>i))==1){
count++;
}
}
System.out.println("num在内存中存储时二进制1的个数为:"+count);
}
}
Note: In the if statement, it cannot be written as num&(1<<i), so the result may be a number such as 1000, which is incorrect.