题目描述
输入一个int型的正整数,计算出该int型数据在内存中存储时1的个数。
输入描述:
输入一个整数(int类型)
输出描述:
这个数转换成2进制后,输出1的个数
示例1
输入
5
输出
2
//最快最省内存方式
public static void main(String[] args) throws Exception {
InputStream stream = System.in;
int l ;
byte[] bytes = new byte[1024];
while ((l = stream.read(bytes)) > 0) {
String numStr = new String(bytes, 0, l - 1);
int num = Integer.parseInt(numStr);
int count = 0;
while(0 != num){
if(num % 2 == 1){
count++;
}
num = num / 2;
}
System.out.println(count);
}
}public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int i = in.nextInt();
in.close();
int count = 0;
//十进制转二进制方法
String s = Integer.toBinaryString(i);
String[] str = s.split("");
for (int j = 0; j < str.length; j++) {
if ("1".equals(str[j])){
count++;
}
}
System.out.println(count);
}public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int i = in.nextInt();
in.close();
int count = 0;
//十进制转二进制算法
while (0 != i) {
if (i % 2 == 1) {
count++;
}
i = i / 2;
}
System.out.println(count);
}
京公网安备 11010502036488号