zl程序教程

您现在的位置是:首页 >  其它

当前栏目

leetcode415---字符串大数相加

字符串 --- 相加 大数
2023-09-27 14:29:12 时间

Given two non-negative numbers num1 and num2 represented as string, return the sum of num1 and num2.

Note:

  1. The length of both num1 and num2 is < 5100.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

 

 

我的第一个想法就是选好两个字符串,然后模拟加法进位,然后用一个字符串接着,同时记住进位,最后返回这个字符串的反转即可。

 

没有想到什么比较好的解决思路

public class Solution {
    public String addStrings(String num1, String num2) {
        StringBuilder sb = new StringBuilder();
        int carry = 0;
        for(int i = num1.length() - 1, j = num2.length() - 1; i >= 0 || j >= 0; i--, j--){
            int x = i < 0 ? 0 : num1.charAt(i) - '0';
            int y = j < 0 ? 0 : num2.charAt(j) - '0';
            sb.append((x + y + carry) % 10);
            carry = (x + y + carry) / 10;
        }
        if(carry != 0)
            sb.append(carry);
        return sb.reverse().toString();
    }
}