Java 19ms "in-place" without StringBuilder


  • 1
    public String addStrings(String num1, String num2) {
        // suppose num1 is shorter
        if(num1.length()>num2.length()) return addStrings(num2, num1);
        char[] arr1 = num1.toCharArray(), arr2 = num2.toCharArray();
        int len1 = arr1.length, len2 = arr2.length, carry = 0;
        for(int i=0; i<len2; ++i){
            int idx1 = len1-i-1, idx2 = len2-i-1;
    
            if(idx1>=0) arr2[idx2] += (arr1[idx1] - '0' +carry);
            else if(carry==0) break;
            else arr2[idx2] += carry;
    
            if(arr2[idx2]>'9'){
                carry = 1;
                arr2[idx2] -= 10;
            } else carry = 0;
        }
        return carry==1 ? "1".concat(String.valueOf(arr2)) : String.valueOf(arr2);
    }
    

  • 0
    H

    How is it in-place? You are using O(n) extra space [O(2n) to be exact]. In-place would mean you are managing the sum in either num1 or num2 while you are adding.


Log in to reply
 

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