美文网首页
[刷题防痴呆] 0415 - 字符串相加 (Add String

[刷题防痴呆] 0415 - 字符串相加 (Add String

作者: 西出玉门东望长安 | 来源:发表于2021-10-23 01:08 被阅读0次

题目地址

https://leetcode.com/problems/add-strings/

题目描述

415. Add Strings

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

You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.

 

Example 1:

Input: num1 = "11", num2 = "123"
Output: "134"
Example 2:

Input: num1 = "456", num2 = "77"
Output: "533"
Example 3:

Input: num1 = "0", num2 = "0"
Output: "0"

思路

  • 从后往前一个接着一个计算.
  • 要判断进位.

关键点

  • 最后的string需要reverse.

代码

  • 语言支持:Java
class Solution {
    public String addStrings(String num1, String num2) {
        StringBuffer sb = new StringBuffer();
        int carry = 0;
        int i = num1.length() - 1;
        int j = num2.length() - 1;

        while (i >= 0 || j >= 0) {
            int sum = 0;
            if (i >= 0) {
                sum += num1.charAt(i) - '0';
                i--;
            }
            if (j >= 0) {
                sum += num2.charAt(j) - '0';
                j--;
            }
            sum += carry;
            sb.append(sum % 10);
            carry = sum / 10;
        }
        if (carry > 0) {
            sb.append(carry);
        }

        return sb.reverse().toString();
    }
}

相关文章

网友评论

      本文标题:[刷题防痴呆] 0415 - 字符串相加 (Add String

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