Straight forward way to AC this problem, Java


  • 0
    H
    public class Solution {
        public String addStrings(String num1, String num2) {
            StringBuilder sb1 = new StringBuilder(num1);
            StringBuilder sb2 = new StringBuilder(num2);
            sb1.reverse();
            sb2.reverse();
            
            char[] array1 = sb1.toString().toCharArray();
            char[] array2 = sb2.toString().toCharArray();
            int carry = 0;
            List<Character> res = new ArrayList<Character>();
            
            for (int i = 0; i < Math.max(array1.length, array2.length); i ++) {
                int tmp1 = i < array1.length ? array1[i]-'0' : 0;
                int tmp2 = i < array2.length ? array2[i]-'0' : 0;
                int tmp = tmp1 + tmp2 + carry;
                carry = tmp / 10;
                tmp = tmp % 10;
                char c = (char)(tmp + '0');
                res.add(c);
            }
            if (carry == 1) res.add('1');
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < res.size(); i ++) {
                sb.append(res.get(i));
            }
            sb.reverse();
            return sb.toString();
        }
    }
    

Log in to reply
 

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