Chris
Chris

Reputation: 437

Binary to Int Using Recursion

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?

Upvotes: 1

Views: 420

Answers (3)

Vikas Satpute
Vikas Satpute

Reputation: 174

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));

}

Upvotes: 0

I. Ahmed
I. Ahmed

Reputation: 2534

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));

}

Upvotes: 1

Thiyagu
Thiyagu

Reputation: 17890

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)

Upvotes: 3

Related Questions