先把十进制数字转成二进制数字的字符串,再将字符串中的“1”全部替换为空,再让替换前字符串的长度减去替换后字符串的长度就是1的个数
import java.util.*;
public class Main{
public static void main(String[] arts){
Scanner sc=new Scanner(System.in);
int num=sc.nextInt();
String str=Integer.toBinaryString(num);
String newStr=str.replaceAll("1","");
System.out.println(str.length()-newStr.length());
}
}
public class Main{
public static void main(String[] arts){
Scanner sc=new Scanner(System.in);
int num=sc.nextInt();
String str=Integer.toBinaryString(num);
String newStr=str.replaceAll("1","");
System.out.println(str.length()-newStr.length());
}
}
//一个数对2取余为1时,其二进制表达式最后一位为1,迭代右移一位来依次判断该数二进制表达式中每一位是否为1,直至数值为0则表明所有位已经判断完毕
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a = in.nextInt();
int result=0;
while(a>0){
if(1==a%2) result++;
a=a>>>1;
}
System.out.println(result);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a = in.nextInt();
int result=0;
while(a>0){
if(1==a%2) result++;
a=a>>>1;
}
System.out.println(result);
}
}
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
int num = sc.nextInt();
//计算1的个数
int count = 0;
String toBinary = Integer.toBinaryString(num);
for(int i = 0; i < toBinary.length(); i++){
char c = toBinary.charAt(i);
if(c == '1'){
count++;
}
}
System.out.println(count);
}
}
}
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
int num = sc.nextInt();
//计算1的个数
int count = 0;
String toBinary = Integer.toBinaryString(num);
for(int i = 0; i < toBinary.length(); i++){
char c = toBinary.charAt(i);
if(c == '1'){
count++;
}
}
System.out.println(count);
}
}
}