Search code examples
javabinaryoctal

Why doesn't my octal-to-decimal converter work for certain cases?


I am working on this octal-to-decimal converter:

public int getDecimal(String input)
{
    int output = 0;

    // reverse input so that it is easier to work with
    input = new StringBuilder(input).reverse().toString();

    for (int c = 0; c < input.length(); c++)
    {
        // check for invalid digit
        if (input.charAt(c) < '0' || input.charAt(c) > '7')
            return 0;

        if (input.charAt(c) != '0')
        {
            if (input.charAt(c) == '1')
                output += Math.pow(8, c);
            else // if it's greater than 1
                output += Math.pow(8, c) + input.charAt(c) - 1;
        }
    }

    return output;
}

It works for about 65% of the test cases, such as converting "10" to "8." However, it does not work for other cases, such as converting "17" to "15." What am I doing wrong?


Solution

  • Your formula is wrong.

    What are you doing at this line,

    output += Math.pow(8, c) + input.charAt(c) - 1;
    

    It should be more like,

    output += Math.pow(8, c) * (input.charAt(c) - '0');
    

    Like, output += 8^(index) * digit.