简体   繁体   中英

Decimal input then Binary input (without using Integer.parseInt)

I am a first year Computer Science student. This question has been asked many times and I have gone through those. But I still could not find where I need to fix in my current code. I have written the code to convert Decimal to Binary. The following is the sample input and output.

Sample Input

4
101
1111
00110
111111

Sample Output

5
15
6
63

I understand the concept and binary conversion. However I am not able to enter binary value for the specified number and am getting incorrect output. I cannot use Integer.parseInt. Below is the rough conversion workout from binary to decimal.

Binary to Decimal 
    1       0       1       0 -binary
    3       2       1       0 -power
    2       2       2       2 -base
    1*2^3 + 0*2^2 + 1*2^1 + 0*2^0
    8     + 0     + 2     + 0     = 10

Code

public class No2_VonNeumanLovesBinary {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int numTotal, binaryNum, decimalNum = 0, remainder;
        numTotal = s.nextInt();
        for(int i = 0 ; i <= numTotal; i++){
        // This is to get binaryNum input. However I am not getting the expected result.
            binaryNum = s.nextInt();
            while(binaryNum != 0){
                remainder = binaryNum % 10;
                decimalNum = decimalNum + (remainder * i);
                i = i * 2;
                binaryNum = binaryNum / 10;
            }
            System.out.println(decimalNum);
        }
    }
}

Thanks!

Two things to fix. Use variable other than i inside while loop. Reset decimalNum to 0 after printing the value. ie,

public static void main(String[] args) {
    Scanner s = new Scanner(System.in);
    int numTotal, binaryNum, decimalNum = 0, remainder;
    numTotal = s.nextInt();
    for(int i = 0 ; i <= numTotal; i++){
        // This is to get binaryNum input. However I am not getting the expected result.
        binaryNum = s.nextInt();
        int j = 1;
        while(binaryNum != 0){
            remainder = binaryNum % 10;
            decimalNum = decimalNum + (remainder * j);
            j = j * 2;
            binaryNum = binaryNum / 10;
        }
        System.out.println(decimalNum);
        decimalNum = 0;
    }       
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM