Java Solution: sb.insert is slower than sb.reverse


  • 0
    T
        public String addStrings(String num1, String num2) {
            if (num1 == "") return num2;
            if (num2 == "") return num1;
            int alen = num1.length() - 1, blen = num2.length() - 1, carry = 0;
            StringBuilder sb = new StringBuilder();
            while (alen > -1 || blen > -1 || carry != 0){
                if (alen > -1){
                    carry += num1.charAt(alen) - '0';
                    alen--;
                }
                if (blen > -1){
                    carry += num2.charAt(blen) - '0';
                    blen--;
                }
                sb.insert(0, carry % 10);
                carry = carry / 10;
            }
            return sb.toString();
        }
    

Log in to reply
 

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