1

I have the following code for a recursive function to convert binary to int:

public static int binaryToInt( String b ) {

    if(b.length() < 2) {
        return 0;
    }

    return b.charAt(0) * (int) Math.pow(2, b.length()) + binaryToInt(b.substring(1));

}

I am not getting the correct values for example: "101" I get 584. I thought my logic is correct but can someone please point out where i am going wrong?

1

3 Answers 3

3

There are quite a few problems

  1. b.charAt(0) * ... - You are multiplying the ASCII value of the character and an int. Change it to b.charAt(0) - '0' to get the actual integer.

  2. Math.pow(2, b.length()) - It has to Math.pow(2, b.length() - 1). Working for a few samples with a pen and paper will explain this.

  3. The base condition is wrong. You need to return when there are no more characters left. So, it must be if(b.length() == 0)
Sign up to request clarification or add additional context in comments.

1 Comment

@Henry Just added that :)
1

First: I changed your base criteria to allow all of the bits in calculation:

if(b.length() <= 0) {
    return 0;
 }

Second: b.charAt(0) return the ASCII value not the integer, so make it integer by using: (b.charAt(0) - '0')

Third: The power of each position will be length-1, so changed as following:

Math.pow(2, b.length()-1)

Final solution:

Please check the final solution:

public static int binaryToInt( String b ) {

    if(b.length() <= 0) {
        return 0;
    }

    return (b.charAt(0) - '0') * (int) Math.pow(2, b.length()-1) + binaryToInt(b.substring(1));

}

Comments

0

The code you have has the following errors:

  1. b.charAt(0)- returns the ASCII value of the character that means result is calculated as ASCCI value (i.e if b.charAt(0) returns 1 then its corresponding ASCII value is 49).

  2. if (b.length() < 2)- You are not checking the value of string what if the value is 1 still it returns 0.

  3. the Math.pow(2, b.length()) to be modified as Math.pow(2, b.length()-1)

Here is the code:

public static int binaryToInt( String b ) {

    if(b.length() < 2) {
        if(b.charAt(0)=='1')
            return 1;
        return 0;
    }

    return Character.getNumericValue(b.charAt(0)) * (int) Math.pow(2, b.length()-1) + binaryToInt(b.substring(1));

}

1 Comment

Please let me know you are satisfied with the answer or not:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.