Java solution with StringBuilder reverse() - 23 ms


  • 0
    Y
    public class Solution {
        public String addStrings(String num1, String num2) {
            if (num1 == null || num1.length() == 0) return num2;
            if (num2 == null || num2.length() == 0) return num1;
            
            int m = num1.length();
            int n = num2.length();
            int carry = 0;
            
            int i = 0;
            int j = 0;
            StringBuilder res = new StringBuilder();
            
            while (i < m || j < n || carry != 0) {
                int x = carry;
                if (i < m) x += (num1.charAt(m - 1 - i) - '0');
                if (j < n) x += (num2.charAt(n - 1 - j) - '0');
                i++;
                j++;
                res.append((char)(x % 10 + '0'));
                carry = x / 10;
            }
            
            return res.reverse().toString();
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.