Straight forward java solution with commnet


  • 0
    /*
    Straight forward solution
    Add the shorter number to the longer number
    has an extra space in the array in case there is a final carry
    */
    
    public class Solution {
        public String addStrings(String num1, String num2) {
            String shortS = (num1.length() < num2.length()) ? num1:num2;
            String longS = (num1.length() < num2.length()) ? num2:num1;
            int[] result = new int[longS.length()+1];
            int carry = 0;
            for(int i = result.length - 1; i >= 1; i--){
                int sum = 0;
                if(shortS.length() >= (result.length - i)){
                    sum = (int)(longS.charAt(i-1) - '0') + (int)(shortS.charAt(shortS.length() - result.length + i) - '0') + carry;
                }else{
                    sum = (int)(longS.charAt(i-1) - '0') + carry;
                }
                result[i] = sum % 10;
                carry = sum / 10;
            }
            StringBuilder sb = new StringBuilder();
            if(carry == 1){
                sb.append('1');
            }
            for(int i = 1; i < result.length; i++){
                sb.append(result[i]);
            }
            return sb.toString();
        }
    }````

Log in to reply
 

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