[LeetCode] 415. Add Strings
Given two non-negative integers num1
and num2
represented as string, return the sum of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 5100. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
字符串相加。题目即是题意。影子题67,这个题是十进制加法,67题是二进制加法。例子,
"13" + "79" = "92"
这个题没有任何算法,考察的是字符串的相关操作。Java和JS的做法略微有一些区别。在Java里面因为有StringBuilder的关系,所以结果里面的每一位上的数字可以被append;JS里面则是用数组代替了StringBuilder的功用。但是两种语言实现的思想是一样的。
时间O(n)
空间O(n)
Java实现
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实现
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 };