GeeksforGeeks二进制转十进制Java代码遇运行时错误,无法通过全部测试用例
问题原因分析
你的代码无法通过所有测试用例,核心问题有两个:
Integer范围溢出引发运行时异常
Java里Integer的取值范围是-2^31到2^31-1(即-2147483648至2147483647)。当输入的二进制字符串长度超过31位时,Integer.parseInt(str)会直接抛出NumberFormatException——因为对应的十进制值超出了Integer的存储上限,这就是你遇到运行时错误的核心原因。依赖整数特性的不严谨处理
你的代码通过把二进制字符串转成整数来逐位处理,虽然短字符串场景能正常运行,但本质是依赖整数自动忽略前导零的特性,一旦字符串长度触及Integer溢出阈值,哪怕带前导零也会触发错误。
修复方案
直接遍历二进制字符串的每一位计算十进制值,彻底避免转整数带来的溢出问题,逻辑也更贴合二进制转十进制的原理:
class Solution { public static int binarytodecimal(String str) { int res = 0; for (int i = 0; i < str.length(); i++) { // 从左到右迭代,每一步将结果乘2(等价于左移一位),再加上当前位的数值 res = res * 2 + (str.charAt(i) - '0'); } return res; } }
如果需要处理超过Integer范围的超长二进制字符串,可以把返回类型改为long,或者直接用BigInteger简化实现:
import java.math.BigInteger; class Solution { public static BigInteger binarytodecimal(String str) { return new BigInteger(str, 2); } }
内容的提问来源于stack exchange,提问作者Shreya Saini
相关产品推荐
相关产品推荐

