25ms Easy to understand. Without any short-cut.


  • 0
    F

    ...
    public class Solution {
    public String addStrings(String num1, String num2) {
    StringBuilder sb = new StringBuilder();
    char[] longArr = num1.length() > num2.length() ? num1.toCharArray() : num2.toCharArray();
    char[] shortArr = num1.length() <= num2.length() ? num1.toCharArray() : num2.toCharArray();

        int carry = 0;
        for(int i = longArr.length-1, j = shortArr.length-1; i >= 0; i--, j--){
            int sum = 0;
            if(j < 0){
                sum += (longArr[i] - '0') + carry;
            }else{
                sum += (longArr[i] - '0') + (shortArr[j] - '0') + carry;
            }
            
            if(sum > 9) carry = 1;
            else carry = 0;
            
            sb.append(sum % 10);
        }
        
        if(carry == 1) sb.append(carry);
        return sb.reverse().toString();
        
    }
    

    }

    1. Better to access through array. -> faster than charAt() accessing
    2. Use reverse at the end instead of calling insert function of string builder for N times. O(2N) better than O(N^2)
    3. I'll accept any comment :) Good luck everyone.

    ...


Log in to reply
 

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