题目
- 题目描述
输入一个int型的正整数,计算出该int型数据在内存中存储时1的个数。 - 输入描述:
输入一个整数(int类型) - 输出描述:
这个数转换成2进制后,输出1的个数 - 示例1
输入
5 - 输出
2
代码
package org.lht.boot.lang.suanfa;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Scanner;
/**
* @author haitao.li
* @description: 题目描述
* 输入一个int型的正整数,计算出该int型数据在内存中存储时1的个数。
* <p>
* 输入描述:
* 输入一个整数(int类型)
* <p>
* 输出描述:
* 这个数转换成2进制后,输出1的个数
* <p>
* 示例1
* 输入
* 复制
* 5
* 输出
* 复制
* 2
* @date 2021/4/15 10:43
*/
public class Huawei求int在内存中1的个数 {
/**
* 除余的方式去计算
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int i = Integer.parseInt(reader.readLine());
int n = 0;
while (i != 0) {
if (i % 2 != 0) {
n++;
}
i = i / 2;
}
System.out.println(n);
}
/**
* 牛客网解法
*
* @param args
* @throws Exception
*/
// 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);
// char[] numChars = Integer.toBinaryString(num).toCharArray();
// int countNum = 0;
// for (int i = 0; i < numChars.length; i++) {
// if (numChars[i] == '1') {
// countNum = countNum + 1;
// }
// }
// System.out.println(countNum);
// }
// }
/**
* 通过位移逐位去判断是否为1
*/
public static int bitCount(int n) {
int count = 0;
while (n != 0) {
count += n & 1;//最后一位与1运算n=7(111) 111&001=1
n >>>= 1;//将最后一位位移出 111>>>1=011
}
return count;
}
//
// public static void main(String[] args) {
// System.out.println(bitCount(15));
// }
}