[Leetcode]415. Add Strings

Given two non-negative integers 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.
整体来说没什么难度啊,注意几个点的就好。 加法要尾巴对齐了加,如果一直有进位,就算一个string结束了也要继续加。
AC Solution:

public class Solution {

    public String addStrings(String num1, String num2) {
        StringBuilder sb = new StringBuilder();
        int l1 = num1.length();
        int l2 = num2.length();
        int carry = 0;
        int sum = 0;
        for(int i = l1 - 1, j = l2 - 1; i>=0 || j>=0 || carry == 1; i--, j--){
            int n1 = i < 0 ? 0 : num1.charAt(i) - '0';
            int n2 = j < 0 ? 0 : num2.charAt(j) - '0';
            sum = (n1 + n2 + carry) % 10;
            sb.insert(0,sum);
            carry = (n1 + n2 + carry) / 10;
        }
        return sb.toString();
    }
}

Comments

Popular posts from this blog

LeetCode] 644.Maximum Average Subarray II

[Leetcode]375. Guess Number Higher or Lower II

[Leetcode] 643. Maximum Average Subarray I