题解 | #求int型正整数在内存中存储时1的个数#
求int型正整数在内存中存储时1的个数
https://www.nowcoder.com/practice/440f16e490a0404786865e99c6ad91c9
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
// public static void main(String[] args) {
// Scanner in = new Scanner(System.in);
// int n = in.nextInt();
// int count = 0;
// for (int i = 0; i < 32; i++) {
// if ((n & 1) == 1) {
// count++;
// }
// //右移1位=/2:>>1,左移=*2:<<
// n = n >>> 1;
// }
// System.out.print(count);
// }
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int count = 0;
for (int i = 0; i < 32; i++) {
if (n%2==1) {
count++;
}
//右移1位=/2:>>1,左移=*2:<<
n = n /2;
}
System.out.print(count);
}
}
无符号右移运算符(>>>)(零填充右移)将左操作数计算为无符号数,并将该数字的二进制表示形式移位为右操作数指定的位数,取模 32。向右移动的多余位将被丢弃,零位从左移入。其符号位变为 0,因此结果始终为非负数。与其他按位运算符不同,零填充右移返回一个无符号 32 位整数。
其实思路一样的,只不过一个是用逻辑运算一个是算术运算,乘除改为向左或向右移位,余数是否为1,改为与1相与判断末位是否为1
查看11道真题和解析