Add Strings

Given two non-negative integers num1 and num2 written as strings, return their sum as a string. You may not use a big-integer library or convert the whole strings to integers directly.

30:00

Add Strings
easy
Free written solution
Topics
Companies

Given two non-negative integers num1 and num2 written as strings, return their sum as a string. You may not use a big-integer library or convert the whole strings to integers directly.

Example 1:
Input: {"num1":"11","num2":"123"}
Output: 134
Constraints:
  • 1≤num1.length,num2.length≤1041 \leq \text{num1.length}, \text{num2.length} \leq 10^4

  • num1 and num2 consist of digits only

  • num1 and num2 have no leading zeros except for the number 0 itself

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"num1":"11","num2":"123"}

Line the numbers up on the right. i starts at the last digit of num1 (index 1), j at the last digit of num2 (index 2), carry = 0.

column addition, right to left

carry
num1
1
1
+ num2
1
2
3
=

current column

total = d1 + d2 + carry → write total % 10, carry = total / 10

result (digits are written ones-first, then reversed)

(empty)

Variables
VariableValue
i1
j2
carry0
DepthFunction Call
Stack empty
0/7