415. Add Strings (Easy)

https://leetcode.com/problems/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.

Solutions

class Solution {

    public String addStrings(String num1, String num2) {
        if (num1 == null) {
            return num2;
        }

        if (num2 == null) {
            return num1;
        }

        String ans = "";

        int len1 = num1.length();
        int len2 = num2.length();

        int carrier = 0;
        for (int i = 0; i < len1 || i < len2; i++) {
            int x = 0;
            int y = 0;
            if (i < len1) {
                x = num1.charAt(len1 - i - 1) - '0';
            }

            if (i < len2) {
                y = num2.charAt(len2 - i - 1) - '0';
            }

            int remainder = (x + y + carrier) % 10;
            ans = remainder + ans;

            carrier = (x + y + carrier) / 10;
        }

        if (carrier != 0) {
            ans = carrier + ans;
        }

        return ans;
    }
}

Incorrect Solutions

References

Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2020-07-03 00:26:46

results matching ""

    No results matching ""