import java.util.Scanner;
public class Day1503 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("请输入一个数:");
int n = s.nextInt();
if(n>=0)
{
int a = 1;//商
int[] b = new int[32]; //余数
int i = 0;
int c = 0; //计数器
while(a != 0)
{
a = n/2;
b[i] = n%2;
n = a;
i++;
}
for(int j=b.length-1; j>=0; j--)
{
if(b[j]==1)
{
c++;
}
}
System.out.print("二进制数中1的个数:");
System.out.println(c);
}
else
{
//无视符号右移位>>>1 向右移位1位,最高位补上0
/*
移位前 11111111 11111111 11111111 11111101(补码)
移位后 01111111 11111111 11111111 11111110(补码),
对应原码 01111111 11111111 11111111 11111110
*/
n = (n>>>1);
int a = 1;//商
int[] b = new int[32]; //余数
int i = 0;
int c = 0; //计数器
while(a != 0)
{
a = n/2;
b[i] = n%2;
n = a;
i++;
}
for(int j=b.length-1; j>=0; j--)
{
if(b[j]==1)
{
c++;
}
}
System.out.print("二进制数中1的个数:");
System.out.println(c+1);//+1表示加上符号位,因为是负数,所以符号位是1
}
}
}
算法练习小题
于 2019-05-11 14:53:28 首次发布