二进制到十进制转换的简单代码中的运行时错误

问题描述 投票:0回答:1

在 Geeks for Geeks 上,我试图解决二进制到十进制转换的基本问题,但它显示运行时错误。我想知道这背后的原因。如果有人知道这个请告诉。

class Solution {
    public static int binarytodecimal(String str) {
                    
        int n=Integer.parseInt(str);
    int res=0;
        int a=1;
    while(n>0)
        {
        int k=n%10;
        res+=k*a;
        a*=2;
        n/=10;
    }
    return res;
    }

}

此代码正常工作,但为什么它没有通过所有测试用例?

java algorithm binary decimal dsa
1个回答
0
投票

int 是一个 32 位有符号数,这意味着它只能准确存储 10 位十进制数字(如果它们是 0 和 1)。这意味着如果给定一个表示 2048 或更多(即 11 位或更多数字)的二进制数,

Integer.parseInt
将失败。

© www.soinside.com 2019 - 2024. All rights reserved.