您的位置:首页 > 其它

华为OJ 初级:求int型数据在内存中存储时1的个数

2016-07-04 09:27 387 查看
题目如下:



下面总共记录了两种方法:

count1:使用Integer中的 toBinaryString方法,将十进制int型转为二进制String类型

count2:使用‘&’运算与 ‘>>>’ 运算

import java.util.Scanner;

public class Cont_IntToBin {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
int input = scanner.nextInt();
int n = count2(input);
System.out.print(n);
scanner.close();
}

private static int count(int num) {
int n = 0;
String str = Integer.toBinaryString(num);     //将int型转换为二进制String类型
for (int i = 0; i < str.length(); i++)
if (str.charAt(i) == '1')
n++;
return n;

}

private static int count2(int num){    //方法2使用'&'和右移'>>>'运算
int n = 0;
while( num != 0){
n += num & 1;                  //当num中二进制字符有'1'时,和'1'进行'&'结果为1,从而可以计算总共有多少个1
num >>>= 1;					   //num右移,每次左边补0
}
return n;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: