简体   繁体   English

将整数转换为二进制并打印数字之和

[英]Convert integer to binary and print the sum of the digits

The code below is supposed to take an integer, convert it to binary, and then print the sum of the digits:下面的代码应该接受一个整数,将其转换为二进制,然后打印数字之和:

Example:例子:

Input = 15 

( 15 in Binary is "1111" and 1+1+1+1 = 4 )

Output = 4

This is the code I have so far.这是我到目前为止的代码。 However, it is not working as expected.但是,它没有按预期工作。 If you input 15 , it returns 0 instead of 4 as explained above:如果您输入15 ,它将返回0而不是4 ,如上所述:

  Scanner in = new Scanner(System.in);
  int X = in.nextInt();

  String binary = Integer.toBinaryString(X);   

  int amount = 0;  
  String input = Integer.toString(X);

  for(int b = 0; b < binary.length(); b++){
     if (binary.charAt(b) == 1){
      amount++;
     }
  }

  System.out.println(amount);

Characters are always single and written in single quotes.字符总是单引号并用单引号书写。

1 is the character which is extracted from String and it should be written in single quotes. 1是从String中提取的字符,应该用单引号写。

Here is the correct code:这是正确的代码:

if (binary.charAt(b) == '1'){
  amount++;
}

Shorter approach:更短的方法:

Scanner in = new Scanner(System.in);
int X = in.nextInt();
String binary = Integer.toBinaryString(X);   
String input = Integer.toString(X)
System.out.println(StringUtils.countMatches(input, "1"));

Binary operations are enougth二元运算就够了

    int p = 0b10000000000000000000000000010101;
    int t = 0;
    for(int i=0; i<32; i++) {
        t += p & 1;
        p = p >> 1;
    }
    System.out.println(t);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM