Skip to content

Latest commit

 

History

History
61 lines (49 loc) · 1.62 KB

415. Add Strings.md

File metadata and controls

61 lines (49 loc) · 1.62 KB

leetcode-cn Daily Challenge on August 3rd, 2020.


Difficulty : Easy

Related Topics : String


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

Note:

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

Solution

  • mine
    • Java
      • Runtime: 2 ms, faster than 96.67%, Memory Usage: 39.6 MB, less than 33.03% of Java online submissions
        // O(N)time
        // O(N)space
        public String addStrings(String num1, String num2) {
            char[] arr1 = num1.toCharArray();
            char[] arr2 = num2.toCharArray();
            int i = arr1.length, j = arr2.length;
            char[] res = new char[Math.max(i, j) + 1];
            int t = 0;
            int k = 0;
            while (i > 0 || j > 0) {
                char c1 = i > 0 ? arr1[i - 1] : '0';
                char c2 = j > 0 ? arr2[j - 1] : '0';
                int sum = c1 - '0' + c2 - '0' + t;
                t = sum / 10;
                res[k++] = (char) (sum % 10 + '0');
                i--;
                j--;
            }
            if (t != 0) res[k++] = (char) (t + '0');
            StringBuilder sb = new StringBuilder();
            while (k > 0) {
                k--;
                sb.append(res[k]);
            }
            return sb.toString();
        }