Java solution using two pointers


  • 0
    P
    public class Solution {
        public String addStrings(String num1, String num2) {
            StringBuilder builder = new StringBuilder();
            int i = num1.length() - 1; 
            int j = num2.length() - 1;
            int carryOn = 0;
            while (i >= 0 && j >= 0) {
                int digit = (num1.charAt(i) - '0') + (num2.charAt(j) - '0') + carryOn;
                carryOn = digit / 10; digit = digit % 10;
                builder.append(digit);
                i -= 1; j -= 1;
            }
            // list 2 runs out of number
            while (i >= 0) {
                int digit = (num1.charAt(i) - '0') + carryOn;
                carryOn = digit / 10; digit = digit % 10;
                builder.append(digit);
                i -= 1;
            }
            
            // list 1 runs out of number
            while (j >= 0) {
                int digit = (num2.charAt(j) - '0') + carryOn;
                carryOn = digit / 10; digit = digit % 10;
                builder.append(digit);
                j -= 1;
            }
            
            if (carryOn == 1) builder.append(carryOn);
            
            return builder.reverse().toString();
        }
    }
    

Log in to reply
 

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