Reputation: 43
/**
* Created by abdul on 10/31/2016.
*/
import java.util.Arrays;
import java.util.Scanner;
public class BitCount {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter Cases:");
int cases = in.nextInt();
for (int i = 0; i < cases; i++) {
int a = in.nextInt();
String binary = Integer.toBinaryString(a);
String[] nums = {binary};
int count = 0;
for (int j = 0; j < nums.length; j++) {
//System.out.println(Arrays.toString(nums));
if (nums[j].equals("1"))
count++;
}
System.out.println(count);
}
}
This is a problem from Code Abbey Called Bit Count As you probably know, all values inside a computer are represented in binary system. In this simple task you are to write a program which counts the number of non-zero bits in a given value.
We are using 32-bit integer values, so there should be from 0 to 32 non-zero bits. http://www.codeabbey.com/index/task_view/bit-count Could you please help me understand why my loop is only incrementing once and not incrementing through the entire thing?
Upvotes: 1
Views: 3477
Reputation: 6780
You do this:
int a = in.nextInt();
String binary = Integer.toBinaryString(a);
String[] nums = {binary};
Let's imagine you enter "4". What happens?
a
. binary
. binary
. What you are trying to do is create an array of each digit of the string, but you actually create a single element array that simply stores another copy of the string you already computed! Try this instead:
int a = in.nextInt();
String binary = Integer.toBinaryString(a);
int count = 0;
for (int j = 0; j < binary.length(); j++) {
//System.out.println(Arrays.toString(nums));
if (binary.charAt(j) == '1')
count++;
}
System.out.println(count);
This will check each character of the binary string for the digit 1.
Upvotes: 2