String concatenation. That topic is still on. 43 shadow problem . example,
"13" + "79" = "92"
This problem does not have any algorithm, the study is related to the operation of the string. Java and JS practice a little there are some differences. Because of the relationship between StringBuilder, so the numbers on the inside of each and every result can be append in Java; JS there is an array instead of StringBuilder function. But the two languages to realize the idea is the same.
Time O (n)
Space O (n)
Java implementation
1 class Solution { 2 public String addStrings(String num1, String num2) { 3 int i = num1.length() - 1; 4 int j = num2.length() - 1; 5 int carry = 0; 6 StringBuilder sb = new StringBuilder(); 7 while (i >= 0 || j >= 0 || carry == 1) { 8 int a = i >= 0 ? num1.charAt(i--) - '0' : 0; 9 int b = j >= 0 ? num2.charAt(j--) - '0' : 0; 10 int sum = a + b + carry; 11 sb.append(sum % 10); 12 carry = sum / 10; 13 } 14 return sb.reverse().toString(); 15 } 16 }
JavaScript implementation
1 /** 2 * @param {string} num1 3 * @param {string} num2 4 * @return {string} 5 */ 6 var addStrings = function(num1, num2) { 7 let i = num1.length - 1; 8 let j = num2.length - 1; 9 let carry = 0; 10 let res = []; 11 while (i >= 0 || j >= 0 || carry == 1) { 12 let digit1 = i < 0 ? 0 : num1.charAt(i) - '0'; 13 let digit2 = j < 0 ? 0 : num2.charAt(j) - '0'; 14 let digitsSum = digit1 + digit2 + carry; 15 res.push(digitsSum % 10); 16 carry = Math.floor(digitsSum / 10); 17 i--; 18 j--; 19 } 20 return res.reverse().join(''); 21 };