-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path415_add_strings.rb
More file actions
36 lines (32 loc) · 1.18 KB
/
415_add_strings.rb
File metadata and controls
36 lines (32 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# Leetcode Problem: https://leetcode.com/problems/add-strings/
#Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
#
# Note:
#
# The length of both num1 and num2 is < 5100.
# Both num1 and num2 contains only digits 0-9.
# Both num1 and num2 does not contain any leading zero.
# You must not use any built-in BigInteger library or convert the inputs to integer directly.
# ----------------------------------------------------------------------------------------------------------------------
# @param {String} num1
# @param {String} num2
# @return {String}
def add_strings(num1, num2)
sum = ''
carry = 0
while num1.length.positive? || num2.length.positive?
last_num1 = num1[0.-1]
num1 = num1.chomp(last_num1) unless last_num1.nil?
last_num2 = num2[0.-1]
num2 = num2.chomp(last_num2) unless last_num2.nil?
current_sum = last_num1.to_i + last_num2.to_i + carry
carry = current_sum/10
sum = (current_sum % 10).to_s + sum
sum = carry.to_s + sum if num1 == '' && num2 == '' && carry != 0
end
sum
end
p add_strings('12', '13')
p add_strings('12', '19')
p add_strings('9', '1')
p add_strings('0', '0')