java题目 求int型正整数在内存中存储时1的个数
输入一个 int 型的正整数,计算出该 int 型数据在内存中存储时 1 的个数。
数据范围:保证在 32 位整型数字范围内
输入描述:
输入一个整数(int类型)
输出描述:
这个数转换成2进制后,输出1的个数
示例1
输入:
5
输出:
2
示例2
输入:
0
输出:
0
1 import java.util.*; 2 3 public class Main{ 4 5 public static void main(String[] args) { 6 Scanner scan = new Scanner(System.in); 7 int val = scan.nextInt(); 8 int count = 0; 9 while(val != 0) { 10 count =count + val & 1; //与1,得1说明该位为1 11 val = val >>> 1; //右移1位,检查下一位 12 } 13 System.out.println(count); 14 } 15 }
方法二
1 import java.io.*; 2 3 public class Main{ 4 public static void main(String[] args) throws IOException{ 5 InputStream input = System.in; 6 int len; 7 byte[] bytes = new byte[1024]; 8 while((len=input.read(bytes))>0){ 9 String numstr = new String(bytes,0,len-1); //通过byte数组,0,总共length-1长的字节构造字符串对象 10 int num=Integer.parseInt(numstr); //转换为int 11 char[] ch = Integer.toBinaryString(num).toCharArray(); //将num转换为二进制字符串,然后将字符串转为字符数组 12 int count = 0; 13 for(int i=0;i<ch.length;i++){ 14 if(ch[i]=='1'){ 15 count=count+1; 16 } 17 } 18 System.out.println(count); 19 } 20 } 21 }