#415
Easy Algorithms Add strings
Math String Simulation
52.1% acceptance
Jan 13, 2026
5435
829
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.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn add_strings(num1: String, num2: String) -> String {
let mut result = Vec::new();
let mut carry = 0;
let mut i = num1.len() as i32 - 1;
let mut j = num2.len() as i32 - 1;
let num1: Vec<u8> = num1.bytes().collect();
let num2: Vec<u8> = num2.bytes().collect();
while i >= 0 || j >= 0 || carry > 0 {
let digit1 = if i >= 0 { (num1[i as usize] - b'0') as i32 } else { 0 };
let digit2 = if j >= 0 { (num2[j as usize] - b'0') as i32 } else { 0 };
let sum = digit1 + digit2 + carry;
result.push((sum % 10) as u8 + b'0');
carry = sum / 10;
i -= 1;
j -= 1;
}
result.reverse();
String::from_utf8(result).unwrap()
}
}