Skip to content

Commit 471948d

Browse files
authored
Merge pull request #100 from fartem/415_Add_Strings
2023-06-13 v. 0.8.1: added "415. Add Strings"
2 parents 5b78bf4 + aae36b1 commit 471948d

File tree

4 files changed

+53
-1
lines changed

4 files changed

+53
-1
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,3 +93,4 @@ Profile on LeetCode: [fartem](https://leetcode.com/fartem/).
9393
| 409. Longest Palindrome | [Link](https://leetcode.com/problems/longest-palindrome/) | [Link](./lib/easy/409_longest_palindrome.rb) |
9494
| 412. Fizz Buzz | [Link](https://leetcode.com/problems/fizz-buzz/) | [Link](./lib/easy/412_fizz_buzz.rb) |
9595
| 414. Third Maximum Number | [Link](https://leetcode.com/problems/third-maximum-number/) | [Link](./lib/easy/414_third_maximum_number.rb) |
96+
| 415. Add Strings | [Link](https://leetcode.com/problems/add-strings/) | [Link](./lib/easy/415_add_strings.rb) |

leetcode-ruby.gemspec

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ require 'English'
55
::Gem::Specification.new do |s|
66
s.required_ruby_version = '>= 3.0'
77
s.name = 'leetcode-ruby'
8-
s.version = '0.8.0'
8+
s.version = '0.8.1'
99
s.license = 'MIT'
1010
s.files = ::Dir['lib/**/*.rb'] + %w[bin/leetcode-ruby README.md LICENSE]
1111
s.executable = 'leetcode-ruby'

lib/easy/415_add_strings.rb

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# frozen_string_literal: true
2+
3+
# https://leetcode.com/problems/add-strings/
4+
# @param {String} num1
5+
# @param {String} num2
6+
# @return {String}
7+
def add_strings(num1, num2)
8+
result = ''
9+
num1_p = num1.length - 1
10+
num2_p = num2.length - 1
11+
addition = 0
12+
while num1_p >= 0 || num2_p >= 0
13+
first = next_num(num1, num1_p)
14+
second = next_num(num2, num2_p)
15+
sum = first + second
16+
if addition == 1
17+
sum += addition
18+
addition = 0
19+
end
20+
if sum >= 10
21+
sum -= 10
22+
addition = 1
23+
end
24+
result += sum.to_s
25+
num1_p -= 1
26+
num2_p -= 1
27+
end
28+
result += addition.to_s if addition == 1
29+
30+
result.reverse
31+
end
32+
33+
# @param {String} num
34+
# @param {Integer} index
35+
# @return {Integer}
36+
def next_num(num, index)
37+
index >= 0 ? num[index].to_i(10) : 0
38+
end

test/easy/test_415_add_strings.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# frozen_string_literal: true
2+
3+
require_relative '../test_helper'
4+
require_relative '../../lib/easy/415_add_strings'
5+
require 'minitest/autorun'
6+
7+
class AddStringsTest < ::Minitest::Test
8+
def test_default
9+
assert_equal('134', add_strings('11', '123'))
10+
assert_equal('533', add_strings('456', '77'))
11+
assert_equal('0', add_strings('0', '0'))
12+
end
13+
end

0 commit comments

Comments
 (0)