美文网首页
Java实现两个大数相加

Java实现两个大数相加

作者: 从头再来123 | 来源:发表于2018-09-30 01:41 被阅读0次
    package leetcode;
    
    import java.util.Arrays;
    
    public class Test {
        public static void main(String[] args) {
            String a = "999";
            String b = "1";
            //将两个字符串分解成数组 分别为arr1和arr2
            int[] arr1 = new int[a.length()];
            int[] arr2 = new int[b.length()];
            for (int i = 0; i < a.length(); i++) {
                arr1[i] = Integer.parseInt(a.substring(i, i + 1));
            }
            for (int i = 0; i < b.length(); i++) {
                arr2[i] = Integer.parseInt(b.substring(i, i + 1));
            }
            System.out.println(Arrays.toString(arr1));
            System.out.println(Arrays.toString(arr2));
            //用carry记录进位值
            int carry = 0;
            int sum = 0;
            int i = arr1.length - 1;
            int j = arr2.length - 1;
            int[] store = new int[a.length() + 1];
            int count = 0;
            //将对应的位相加
            while (i >= 0 || j >= 0) {
                int num1 = i < 0 ? 0 : arr1[i];
                int num2 = j < 0 ? 0 : arr2[j];
                sum = carry + num1 + num2;
                carry = sum / 10;
                store[count++] = sum % 10;
                i--;
                j--;
            }
            //保存最后一次进位值
            store[count] = carry;
            System.out.println(Arrays.toString(store));
            //如果最后一次进位值为0则舍去
            int f = carry == 0 ? store.length - 2 : store.length - 1;
            StringBuffer sb = new StringBuffer();
            //将所得结果拼接
            for (int a1 = f; a1 >= 0; a1--) {
                sb.append(store[a1]);
            }
            System.out.println(sb);
        }
    }
    

    相关文章

      网友评论

          本文标题:Java实现两个大数相加

          本文链接:https://www.haomeiwen.com/subject/zceioftx.html