Skip to content

Instantly share code, notes, and snippets.

@jlcarrascof
Created October 7, 2023 05:03
Show Gist options
  • Save jlcarrascof/1bb16d2a02a64ce4e9801a72e956269f to your computer and use it in GitHub Desktop.
Save jlcarrascof/1bb16d2a02a64ce4e9801a72e956269f to your computer and use it in GitHub Desktop.
Add Strings
"""
Adds two strings representing non-negative integers.
Args:
num1: A string representing a non-negative integer.
num2: A string representing a non-negative integer.
Returns:
A string representing the sum of num1 and num2.
"""
def add_strings(num1, num2)
i = num1.length - 1
j = num2.length - 1
carry = 0
result = ''
while i >= 0 || j >= 0
n1 = i >= 0 ? num1[i].ord - '0'.ord : 0
n2 = j >= 0 ? num2[j].ord - '0'.ord : 0
sum = n1 + n2 + carry
carry = sum / 10
result = (sum % 10).to_s + result
i -= 1
j -= 1
end
if carry > 0
result = carry.to_s + result
end
result
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment