描述 |
|
---|---|
知识点 | 位运算 |
运行时间限制 | 10M |
内存限制 | 128 |
输入 | 输入一个整数 |
输出 | 计算整数二进制中1的个数 |
样例输入 | 5 |
样例输出 | 2 |
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner sca = new Scanner(System.in);
int n = sca.nextInt();
sca.close();
System.out.println(findNumberOf1(n));
}
public static int findNumberOf1(int n)
{
int count=0;
int num=1;
for(int i = 1;i <= Integer.SIZE; i++,num *= 2)
{
if((n & num) != 0)
count++;
}
return count;
}
}
我真是醉了,这道题根本不知道它的负数怎么计算,不知道负数二进制的长度算多少,也不知道用补码还是原码表示,做了好多遍,仔细看了一下下面的评论才知道怎么做的,本来睡觉前看见这道题决定挺简单的,谁知道折腾到这个点儿……