Java - Short and simple solution


  • 0
    S
        public String addStrings(String num1, String num2) {
            int len1 = num1.length() - 1;
            int len2 = num2.length() - 1;
            int carry = 0, sum = 0;
            StringBuilder sb = new StringBuilder();
            while(len1 >= 0 || len2 >= 0) {
                int num1Digit = len1 >= 0 ? num1.charAt(len1--)-'0' : 0;
                int num2Digit = len2 >= 0 ? num2.charAt(len2--)-'0' : 0;
                sum = carry;
                carry = 0;
                sum = sum + num1Digit + num2Digit;
                if(sum > 9){
                    sum = sum % 10;
                    carry = 1;
                }
                sb.append(sum);
            }
            if(carry == 1)
              sb.append(carry);
            return sb.reverse().toString();
        }
    

Log in to reply
 

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