将字符串中的数字转换为以 10 为基数的数字

Converting numbers in string to base 10 number

package code;

public class convert {

public int getPower(int power, int base){
    int ans = 1;
    for(int i=0; i<power; i++){
        ans = ans * base;

    }
    return ans;
}

public int baseten (String s, int base){
    int ret = 0;
    for(int i = 0; i<s.length(); i++){
        char cur = s.charAt(i);

        if(base >= 0 && base <= 9){
            int p = getPower(i, base);
            int v = p * (cur - '0');
            ret += v;   

        }

    }

    return ret;


    }
}

这应该采用一个字符串和一个 int 以及 return 该数字的以 10 为底的值。例如 ("1001", 2) should return 9。它目前为我提供了几个不同测试的错误答案,我不确定为什么。非常感谢!

您计算幂次的顺序错误,将最高权重赋予了最后一位而不是第一位。

实际上,您不需要计算每个数字的幂;相反,您可以直接乘以累加器:

for(int i = 0; i<s.length(); i++){
    char cur = s.charAt(i);
    if(base >= 0 && base <= 9){
        ret = ret * base + (cur - '0');
    }
}

这样做与在纸上写数字一样有效。如果你写“10”,然后你在后面写另一个数字,那么这个值就会变大十倍(或者两倍,或者你的基数是多少)。您添加另一个数字,它再次变大十倍(或两倍,或其他)。

我们必须直接考虑数十、数百和数千列的唯一原因是当我们大声朗读十进制数时我们必须使用正确的词。

You getting wrong result just because of your binary conversion is not correct. Because when your string character s[0] the base power should be s.length()-1-i;

For Example: 0101 as input if i = 0 then 0*2^3+ if i = 1 then 1*2^2+ if i = 2 0*2^1+ if i = 3 1*2^0 it produce the result: 5

但是在你的代码中它会产生 10。

Here you have to declare a new variable called j int ret = 0,j = s.length()-1; and initialize it to the string length()-1 after that you have to pass the variable to the getPower() function like this: int p = getPower(j, base);

包代码;

public class convert {

public int getPower(int power, int base){
    int ans = 1;
    for(int i=0; i<power; i++){
        ans = ans * base;

    }
    return ans;
}

public int baseten (String s, int base){
    int ret = 0,j = s.length()-1;
    for(int i = 0; i<s.length(); i++,j--){
        char cur = s.charAt(i);

        if(base >= 0 && base <= 9){
            int p = getPower(j, base);
            int v = p * (cur - '0');
            ret += v;   
        }
    }
    return ret;
    }
}

你也可以一行完成:

int decimalVal = Integer.parseInt("0010101010",2);

它将产生二进制字符串的十进制值。