[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.
整体来说没什么难度啊,注意几个点的就好。 加法要尾巴对齐了加,如果一直有进位,就算一个string结束了也要继续加。
AC Solution:
AC Solution:
public class Solution { public String addStrings(String num1, String num2) { StringBuilder sb = new StringBuilder(); int l1 = num1.length(); int l2 = num2.length(); int carry = 0; int sum = 0; for(int i = l1 - 1, j = l2 - 1; i>=0 || j>=0 || carry == 1; i--, j--){ int n1 = i < 0 ? 0 : num1.charAt(i) - '0'; int n2 = j < 0 ? 0 : num2.charAt(j) - '0'; sum = (n1 + n2 + carry) % 10; sb.insert(0,sum); carry = (n1 + n2 + carry) / 10; } return sb.toString(); } }
Comments
Post a Comment