Description
Given two non-negative integers, num1
and num2
represented as string, return the sum of num1
and num2
as a string.
You must solve the problem without using any built-in library for handling large integers (such as BigInteger
). You must also not convert the inputs to integers directly.
Examples:
Example 1:
Input: num1 = "11", num2 = "123"
Output: "134"
Example 2:
Input: num1 = "456", num2 = "77"
Output: "533"
Example 3:
Input: num1 = "0", num2 = "0"
Output: "0"
Solution in Python
Approach:
- Reverse the Strings:
- Start from the least significant digit (rightmost digit) of both strings to simulate manual addition.
- Simulate Digit-by-Digit Addition:
- Use a carry variable to keep track of overflow during addition.
- Iterate through the digits of both numbers simultaneously, adding them along with the carry.
- Handle Unequal Lengths:
- Continue adding the remaining digits of the longer string once the shorter string is exhausted.
- Handle Remaining Carry:
- If there’s a carry left after processing all digits, append it to the result.
- Construct the Result:
- Reverse the result list since addition starts from the least significant digit.
- Return the Result as a String:
- Join the list of characters to form the final result string.
Python
class Solution:
def addStrings(self, num1: str, num2: str) -> str:
"""
Adds two non-negative integers represented as strings.
:param num1: str - The first non-negative integer as a string.
:param num2: str - The second non-negative integer as a string.
:return: str - The sum of the two numbers as a string.
"""
# Initialize variables
i, j = len(num1) - 1, len(num2) - 1 # Pointers to the last digits of both strings
carry = 0 # To store the carry-over during addition
result = [] # To store the result digits
# Perform addition until all digits are processed
while i >= 0 or j >= 0 or carry:
# Get the digit from num1 if within bounds, otherwise 0
digit1 = int(num1[i]) if i >= 0 else 0
# Get the digit from num2 if within bounds, otherwise 0
digit2 = int(num2[j]) if j >= 0 else 0
# Calculate the sum of the digits plus any carry
total = digit1 + digit2 + carry
# Append the least significant digit of the total to the result
result.append(str(total % 10))
# Update the carry (most significant digit of the total)
carry = total // 10
# Move to the next digits
i -= 1
j -= 1
# Reverse the result and join it to form the final string
return ''.join(reversed(result))
Explanation of the Code:
- Pointers
i
andj
:- These point to the current digit being processed in
num1
andnum2
, starting from the least significant digit.
- These point to the current digit being processed in
- Carry Handling:
- During each iteration, add the carry from the previous addition.
- Update the carry for the next iteration.
- Result Construction:
- Store each digit of the result in a list.
- Reverse the list at the end to convert it from least significant digit first to most significant digit first.
- Edge Cases:
- If one string is longer than the other, process the remaining digits.
- If there’s a leftover carry after processing all digits, append it to the result.
Solution in C++
C++
class Solution {
public:
string addStrings(string num1, string num2) {
// Result string to store the final sum
string result = "";
// Pointers to traverse the strings from the end (least significant digit)
int i = num1.size() - 1;
int j = num2.size() - 1;
// Variable to keep track of carry
int carry = 0;
// Loop until both strings are fully traversed or there is no carry
while (i >= 0 || j >= 0 || carry > 0) {
// Extract the current digit from num1 and num2, if available
int digit1 = (i >= 0) ? num1[i] - '0' : 0;
int digit2 = (j >= 0) ? num2[j] - '0' : 0;
// Compute the sum of digits and the carry
int sum = digit1 + digit2 + carry;
// Update carry for the next iteration
carry = sum / 10;
// Append the last digit of the sum to the result
result += (sum % 10) + '0';
// Move to the next digits in the strings
i--;
j--;
}
// Since the result is constructed in reverse order, reverse it
reverse(result.begin(), result.end());
return result;
}
};
Solution in Javascript
JavaScript
var addStrings = function(num1, num2) {
// Initialize variables:
// i and j are pointers for num1 and num2, starting from the least significant digits (rightmost digits).
// carry will keep track of any carry-over during addition.
// result will store the final sum as a string (reversed initially).
let i = num1.length - 1;
let j = num2.length - 1;
let carry = 0;
let result = [];
// Process both strings from the least significant to the most significant digit.
while (i >= 0 || j >= 0 || carry > 0) {
// Get the digit from num1, or 0 if i is out of bounds.
const digit1 = i >= 0 ? num1.charCodeAt(i) - '0'.charCodeAt(0) : 0;
// Get the digit from num2, or 0 if j is out of bounds.
const digit2 = j >= 0 ? num2.charCodeAt(j) - '0'.charCodeAt(0) : 0;
// Calculate the sum of the digits and the carry.
const sum = digit1 + digit2 + carry;
// The new carry is the integer division of sum by 10.
carry = Math.floor(sum / 10);
// Append the least significant digit of the sum to the result array.
result.push(sum % 10);
// Move to the next digits.
i--;
j--;
}
// Reverse the result array to form the correct sum as a string.
return result.reverse().join('');
};
Solution in Java
Java
class Solution {
public String addStrings(String num1, String num2) {
// Initialize StringBuilder to build the result
StringBuilder result = new StringBuilder();
// Pointers to iterate through the strings from right to left
int i = num1.length() - 1;
int j = num2.length() - 1;
// Variable to hold the carry value
int carry = 0;
// Loop until both strings are fully traversed or carry remains
while (i >= 0 || j >= 0 || carry > 0) {
// Get the current digit from num1, or 0 if index out of bounds
int digit1 = i >= 0 ? num1.charAt(i) - '0' : 0;
// Get the current digit from num2, or 0 if index out of bounds
int digit2 = j >= 0 ? num2.charAt(j) - '0' : 0;
// Compute the sum of the digits and the carry
int sum = digit1 + digit2 + carry;
// Update the carry (sum / 10)
carry = sum / 10;
// Append the current digit (sum % 10) to the result
result.append(sum % 10);
// Move to the next digits in num1 and num2
i--;
j--;
}
// Reverse the result to obtain the final sum as a string
return result.reverse().toString();
}
}