Simple Java Solution using array


  • 0
    E
    public class Solution {
        public String addStrings(String num1, String num2) {
            if(num1.length()==0&&num2.length()==0) return "";
            char[] num11 = num1.toCharArray();
            char[] num22 = num2.toCharArray();
            char[] res = new char[Math.max(num11.length,num22.length)+1];
            Arrays.fill(res,'0');
            int i = num11.length - 1,j = num22.length - 1, k = res.length - 1;
            while(k>=0){
                int value = res[k] - '0';
                if(i>=0) value += (num11[i--] - '0');
                if(j>=0) value += (num22[j--] - '0');
                if(value>=10){
                    res[k-1] = '1';
                    res[k] = (char)('0'+value%10);
                }else res[k] = (char)('0'+value);
                k--;
            }
            k=0;
            while(k<res.length - 1 && res[k]=='0') k++;
            return String.valueOf(res,k,res.length - k);
        }
    }
    

Log in to reply
 

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