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:
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.
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.