JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

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

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"

Constraints:

1 <= num1.length, num2.length <= 104 num1 and num2 consist of only digits. num1 and num2 don’t have any leading zeros except for the zero itself.

Code

class Solution {
    public String addStrings(String num1, String num2) {
        int len1 = num1.length();
        int len2 = num2.length();

        String str1 = new StringBuilder(num1).reverse().toString();
        String str2 = new StringBuilder(num2).reverse().toString();

        int carry = 0;
        StringBuilder res = new StringBuilder();
        
        for(int i = 0; i < Math.max(len1, len2); i++){
            int x = i >= len1 ? 0 : (str1.charAt(i) - '0');
            int y = i >= len2 ? 0 : (str2.charAt(i) - '0');
            int sum = x + y + carry;
            
            res.append(String.valueOf(sum % 10));
            carry = sum / 10;
        }

        if(carry != 0){
            res.append(String.valueOf(carry));
        }

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