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.
题目标签:Math
题目给了我们两个string,让我们相加。
分别记录两个string 数字的长度,从右到左的顺序,把两个数字的 digits 和 carry 相加,处理好carry,如果有数字已经走完的话,只要把它设为 0就可以了。
要注意最后还要检查一下carry,比如 “9” 和 “1” 的情况,最后要把 '1' 加上。
具体请看以下code。
Java Solution:
Runtime beats 54.16%
完成日期:06/17/2017
关键词:math: sum
关键点:从右到左的顺序遍历;用 char - ‘0’ 来取得值
1 class Solution 2 { 3 public String addStrings(String num1, String num2) 4 { 5 int carry = 0; 6 int pos1 = num1.length() - 1; 7 int pos2 = num2.length() - 1; 8 9 String sum = ""; 10 11 while(pos1 >= 0 || pos2 >= 0) 12 { 13 int d1 = 0; 14 int d2 = 0; 15 int tempSum = 0; 16 17 if(pos1 >= 0) // get digit from num1 18 d1 = num1.charAt(pos1) - '0'; 19 20 if(pos2 >= 0) // get digit from num2 21 d2 = num2.charAt(pos2) - '0'; 22 23 24 tempSum = carry + d1 + d2; 25 26 if(tempSum >= 10) // check for carry 27 { 28 carry = 1; 29 tempSum -= 10; 30 } 31 else 32 { 33 carry = 0; 34 } 35 36 sum = tempSum + sum; // add this digit into sum 37 38 pos1--; 39 pos2--; 40 } 41 42 if(carry == 1) // check for last carry 43 sum = '1' + sum; 44 45 return sum; 46 } 47 }
参考资料:n/a
LeetCode 题目列表 - LeetCode Questions List
题目来源:https://leetcode.com/