-9

What is the problem with my code. It prints 1 for any value of input.

package Assign;
import java.util.Scanner;
import java.lang.*;

public class Assignment {

public static void main(String[] args) {
    Scanner s = new Scanner(System.in);
    int num = s.nextInt();
    int x = 1;
    int sum = 1, i = 0;

    while (num > 0) {
        x = num % 10;
        if (x == 1) {
            sum = sum + (2 * i);
        }
        num = num / 10;
        i++;
    }
    System.out.println(sum);
}
}
jmj
  • 237,923
  • 42
  • 401
  • 438

4 Answers4

0

Two problems:

1) You need to add 2^i to sum, not 2*i

2) Sum starts at 1 instead of 0, meaning the answer will always be 1 more than it should be.

EKW
  • 2,059
  • 14
  • 24
0

If you do not need to develop the algorithm yourself, here is a shorter way to do it:

System.out.println(new BigInteger(String.valueOf(num), 2));
JensS
  • 1,151
  • 2
  • 13
  • 20
0

A simple way to do this.

System.out.println(Integer.parseInt(binaryString,2));
Rohit-Pandey
  • 2,039
  • 17
  • 24
0

In the program the only case where the variable sum is getting modified when (num > 0) is in the if block. Considering the if block

if (x == 1) {
   sum = sum + (2 * i);
}

since the variable i = 0.

sum = sum + (2 * i);

evaluates to

sum = sum + (2 * 0);
sum = sum + 0;
sum = sum;

since the variable sum = 1, the output is always 1.

Considering the other possibility, when (num <= 0) where while loop is skipped, since sum = 1, the output is 1.

For Binary to Decimal number converter in Java check out

http://www.java2novice.com/java-interview-programs/binary-to-decimal/