Java 为什么';我的八进制到十进制转换器在某些情况下不能工作吗?

Java 为什么';我的八进制到十进制转换器在某些情况下不能工作吗?,java,binary,octal,Java,Binary,Octal,我正在研究这个八进制到十进制的转换器: 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++) {

我正在研究这个八进制到十进制的转换器:

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;
}
public int getDecimal(字符串输入)
{
int输出=0;
//反向输入,以便更容易使用
输入=新建StringBuilder(输入).reverse().toString();
对于(int c=0;c'7')
返回0;
如果(输入字符(c)!=“0”)
{
如果(输入字符(c)='1')
输出+=数学功率(8,c);
else//如果大于1
输出+=数学功率(8,c)+输入字符(c)-1;
}
}
返回输出;
}

它适用于大约65%的测试用例,例如将“10”转换为“8”。但是,它不适用于其他用例,例如将“17”转换为“15”。我做错了什么?

您需要记住“17”的含义:1*8+7。你的算法错了。您不需要反转字符串。对于通过循环的每次迭代,只需将前一个
输出值
乘以基数(在本例中为8),然后将下一个数字的值相加。继续,直到字符串结束。

您的公式错误

你在这条线上干什么

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

output += Math.pow(8, c) * (input.charAt(c) - '0');
例如,
output+=8^(index)*位

您可以使用以下方法:

input = new StringBuilder(input).reverse().toString();

System.out.println("input:"+input);

for (int c = 0; c < input.length(); c++) {
    output += Integer.parseInt(input.charAt(c) + "") * Math.pow(8, c);

    System.out.println("output:" + output);
}
input=newstringbuilder(input.reverse().toString();
System.out.println(“输入:”+输入);
对于(int c=0;c
这里至少有两个虫子。你可以把这一切简化为

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

取消倒车步骤后。不要担心0和1的特殊情况。

您也可以尝试,无需反转字符串:

public static int getDecimal() {
    int output = 0;
    String input="17"; //by example
    int c=input.length();
    int i=0;
    while(c > 0) {
        if (input.charAt(i) < '0' || input.charAt(i) > '7') {
            return 0;
        }
        output += Math.pow(8, c-1) * Integer.parseInt(input.charAt(i++)+"");
        c--;
    }
    return output;
}
publicstatic int getDecimal(){
int输出=0;
String input=“17”;//举例说明
int c=input.length();
int i=0;
而(c>0){
if(input.charAt(i)<'0'| | input.charAt(i)>'7'){
返回0;
}
output+=Math.pow(8,c-1)*Integer.parseInt(input.charAt(i++)+“”);
c--;
}
返回输出;
}

您的方法似乎没有使用
输入
参数。要获得8^c,请使用
1我的方法现在有一个
输入
参数。
public static int getDecimal() {
    int output = 0;
    String input="17"; //by example
    int c=input.length();
    int i=0;
    while(c > 0) {
        if (input.charAt(i) < '0' || input.charAt(i) > '7') {
            return 0;
        }
        output += Math.pow(8, c-1) * Integer.parseInt(input.charAt(i++)+"");
        c--;
    }
    return output;
}