415. 字符串相加


categories: [Blog,Algorithm]

####


####

415. 字符串相加

难度简单 320
给定两个字符串形式的非负整数 num1num2 ,计算它们的和。

提示:

  1. num1num2 的长度都小于 5100
  2. num1num2 都只包含数字 0-9
  3. num1num2 都不包含任何前导零
  4. 你不能使用任何內建 BigInteger 库,  也不能直接将输入的字符串转换为整数形式。

415. 字符串相加

class Solution {
    public String addStrings(String num1, String num2) {
        int i = num1.length() - 1, j = num2.length() - 1, add = 0;
        StringBuffer ans = new StringBuffer();
        while (i >= 0 || j >= 0 || add != 0) {
            int x = i >= 0 ? num1.charAt(i) - '0' : 0;///长度不一样
            int y = j >= 0 ? num2.charAt(j) - '0' : 0;
            int result = x + y + add;
            ans.append(result % 10);
            add = result / 10;
            i--;
            j--;
        }
        // 计算完以后的答案需要翻转过来
        ans.reverse();
        return ans.toString();

// 作者:LeetCode-Solution
// 链接:https://leetcode-cn.com/problems/add-strings/solution/zi-fu-chuan-xiang-jia-by-leetcode-solution/
    }
}

文章作者:   future
版权声明:   本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 future !
 上一篇
70.爬楼梯 70.爬楼梯
70. 爬楼梯 public int climbStairs(int n) &#123; int p = 1, q = 1, r = 1; for (int i = 2; i <= n; +
2021-02-27 future
下一篇 
459. 重复的子字符串 459. 重复的子字符串
https://leetcode-cn.com/problems/repeated-substring-pattern/solution/zhong-fu-de-zi-zi-fu-chuan-by-leetcode-solution/ 45
2021-02-27 future
  目录