415. Add Strings
LeetCode 415. Add Strings
Description
Given two non-negative integers, num1
and num2
represented as string, return the sum of num1
and num2
as a string.
Example 1:
Example 2:
Constraints:
1 <= num1.length, num2.length <= 104
num1
andnum2
consist of only digits.num1
andnum2
don't have any leading zeros except for the zero itself.
Follow up: Could you solve it without using any built-in BigInteger
library or converting the inputs to integer directly?
Tags
String
Solution
Loop to add characters from "the lowest bit" of both strings, and the loop condition is neither of two pointers is out of index, or the carry bit is non-zero. Obtained the sum of two bits and the carry, we update the result string by concatenating string(sum%10)
and the old result string, meaning that we combining the single digit of the current summation, which is the result of a higher bit, with the lower bits that we have already calculated. Meanwhile, do not forget to update the carry. Finally return the result string.
Complexity
Time complexity: ,
n
for the length of the longer stringSpace complexity:
Code
Reference
Last updated
Was this helpful?