java 21ms without stringBuilder


  • 0
    Z
    public class Solution {
        public String addStrings(String num1, String num2) {
           char[] sumChars = new char[Math.max(num1.length(), num2.length()) + 1];
            int sum = 0;
            for (int i = num1.length() - 1, j = num2.length() - 1, k = sumChars.length - 1; i >= 0 || j >= 0; i--, j--, k--) {
                sum /= 10;
                sum = sum + (i >= 0 ? num1.charAt(i) - '0' : 0);
                sum = sum + (j >= 0 ? num2.charAt(j) - '0' : 0);
                sumChars[k] = (char) (sum % 10 + '0');
            }
    
            if (sum / 10 == 1) {
                sumChars[0] = '1';
            }
    
            if (sumChars[0] != '1') {
                return new String(sumChars, 1, sumChars.length - 1);
            } else {
                return new String(sumChars);
            }
        }
    }
    

Log in to reply
 

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