You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java数组拼接数字加1出现数值异常问题求助

问题排查:数组转数字加1出现溢出异常

代码示例

import java.util.*;

public class Main
{
    public static int plusOne(int[] digits) {
        int no =0;
        for(int i=0; i< digits.length; i++){
            if(digits[i]==0){
                no = no*10;
            }
            else{
                no = no*10+ digits[i];
            }
            
        }
        no = no+1;
        return no;
    }
    public static void main(String[] args) {
        System.out.println("Hello World");
        int arr[] = {9,8,7,6,5,0,4,3,2,1,0};
        
        System.out.println(plusOne(arr));
        
    }
}

问题详情

  • 预期输出:98765043211
  • 实际输出:-19204598
  • 异常现象:循环执行到i==9时,变量no变为随机异常值

原因分析

这是典型的整数溢出问题:

  • Java中int类型的取值范围是-2147483648到2147483647,你要计算的目标数字98765043211远超出这个范围。当no的数值超过int最大值时,会触发溢出,数值会绕回最小值开始计算,最终出现负数或随机异常值。
  • 你尝试的double类型也无法解决问题:double的有效精度只有15-17位,当数字长度超过这个范围时,会丢失末尾的精度,无法准确存储完整数值。

解决方案

方案1:字符串拼接+BigInteger处理(最直观)

直接将数组元素拼接为字符串,再借助BigInteger完成加1操作,完全避免溢出和精度丢失:

public static String plusOne(int[] digits) {
    StringBuilder sb = new StringBuilder();
    for (int digit : digits) {
        sb.append(digit);
    }
    return new java.math.BigInteger(sb.toString()).add(java.math.BigInteger.ONE).toString();
}

调用时直接打印返回的字符串,即可得到准确结果98765043211。

方案2:直接用BigInteger构建数字

如果不想通过字符串中转,可以直接用BigInteger逐步构建目标数字:

import java.math.BigInteger;

public static BigInteger plusOne(int[] digits) {
    BigInteger no = BigInteger.ZERO;
    for (int digit : digits) {
        no = no.multiply(BigInteger.TEN).add(BigInteger.valueOf(digit));
    }
    return no.add(BigInteger.ONE);
}

这种方式同样能精准处理超大数字,不会出现任何精度问题。

内容的提问来源于stack exchange,提问作者Mayank Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 07:43:18