I've been doodling around with this little piece of code that's supposed to calculate and print out which powers of 2 are summarized into a given number. It works fine with small odd numbers but gets lost when I want it to calculate even numbers or bigger ones.
I don't even know what I could try, the code looks alright, but I probably keep failing to notice.
System.out.println("Give a number");
int gigaInt = si.nextInt();
String gigaBit = Integer.toBinaryString(gigaInt);
String[] gigaBitArray = gigaBit.split("");
System.out.println("Binary: " + gigaBit);
List<Integer> powers = new ArrayList<Integer>();
for(int counter = gigaBitArray.length-1; counter >= 0; counter--){
if (gigaBitArray[counter].equals("1"))
powers.add((int)Math.pow(2,counter));
else if(gigaBitArray[counter].equals("0")){
powers.add(0);
}
}
System.out.println("Powers: " + powers);
So, obviously, the program is supposed to calculate the powers, and it does! in some cases... here, when given 9
Give a number 9 Binary: 1001 Powers: [8, 0, 0, 1]
But when I want it to calculate an even number, it always shows "1" as the only component, like this:
Give a number 8 Binary: 1000 Powers: [0, 0, 0, 1]
And whenever asked to deal with a big number, it just goes completely crazy:
Give a number 542 Binary: 1000011110 Powers: [0, 256, 128, 64, 32, 0, 0, 0, 0, 1]
I would be amazingly grateful for any kind of advice on this. It's probably just an infantile kind of mistake, so please, do point it out.