Please implement a function, input an integer, and output the number of 1s in the binary representation of the number.
Method 1: Move 1 (Move to the left)
import java.util.Scanner;
public class LianXi {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int N = in.nextInt();
//二进制转化
System.out.println(Integer.toString(N,2));
int count = 0;
//因为整数有32位,所以进行32次循环
for(int i = 0; i < 32; i++){
/*将二进制转化后的整数与1左移i为得到的数进行与运算,
如果等于1左移i为得到的数,说明有1。*/
if((N&(1<<i)) == (1<<i)){
count++;
}
}
System.out.println(count);
}
}
Method 2: Shift the binary number (shift to the right)
import java.util.Scanner;
public class LianXi {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int N = in.nextInt();
//二进制转化
System.out.println(Integer.toString(N,2));
int count = 0;
//因为整数有32位,所以进行32次循环
for(int i = 0; i < 32; i++){
/*将二进制转化后的整数向右挪i位和1进行与运算,
如果等于1,说明有1。*/
if(((N>>i)&1) == 1){
count++;
}
}
System.out.println(count);
}
}
Method three: subtraction operation (recursively subtract 1 from a binary number)
import java.util.Scanner;
public class LianXi {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int N = in.nextInt();
//二进制转化
System.out.println(Integer.toString(N,2));
int count = 0;
/* 转化后的二进制数减1和自身做与运算,将会消掉最低位的1。
以此往复最终将二进制数变成0,并以此为终止条件。
*/
while(N!=0){
N = ((N-1)&N);
count++;
}
System.out.println(count);
}
}