The problem is that Math.pow
returns a floating-point number, and you're doing floating-point calculations where you think you're doing integer calculations. When i
is 4, and you calculate
b/Math.pow(10,i)%10*Math.pow(2,i);
the calculation goes like this:
b = 11001
b / Math.pow(10,i) = b / 10000 = 1.1001 (not 1)
1.1001 % 10 = 1.1001
1.1001 * Math.pow(2,i) = 1.1001 * 16 = 17.6016 (not 16)
This is then cast to an (int)
when you add it to decimal
. It truncates the last value to 17, but it's too late.
Casting the Math.pow
results to an (int)
will make it work. But this isn't the right approach anyway. If you want to learn how to do it yourself instead of using parseInt
, it's best to input the number as a String
(see my earlier comment), and then you don't have to worry about picking off the bits as decimal digits or powers of 10 at all anyway. Even using your approach, instead of Math.pow
it would be simpler to keep powerOf10
and powerOf2
integer variables that you modify with powerOf10 *= 10; powerOf2 *= 2;
in each loop iteration.