diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/solution/001.Two Sum/Solution.rb b/solution/001.Two Sum/Solution.rb new file mode 100644 index 0000000000000..fbdbcc8ad3747 --- /dev/null +++ b/solution/001.Two Sum/Solution.rb @@ -0,0 +1,11 @@ +# @param {Integer[]} nums +# @param {Integer} target +# @return {Integer[]} +def two_sum(nums, target) + nums.each_with_index do |x, idx| + if nums.include? target - x + return [idx, nums.index(target - x)] if nums.index(target - x) != idx + end + next + end +end \ No newline at end of file diff --git a/solution/002.Add Two Numbers/Solution.rb b/solution/002.Add Two Numbers/Solution.rb new file mode 100644 index 0000000000000..1bed3e860aaf5 --- /dev/null +++ b/solution/002.Add Two Numbers/Solution.rb @@ -0,0 +1,51 @@ +# Definition for singly-linked list. +# class ListNode +# attr_accessor :val, :next +# def initialize(val) +# @val = val +# @next = nil +# end +# end + +# @param {ListNode} l1 +# @param {ListNode} l2 +# @return {ListNode} +def add_two_numbers(l1, l2) + return l2 if l1 == nil + return l1 if l2 == nil + cur_val = l1.val + l2.val + l3 = ListNode.new(cur_val % 10) + add = cur_val >= 10 ? 1 : 0 + tmp = l3 + + l1 = l1.next + l2 = l2.next + while !l1.nil? && !l2.nil? + cur_val = l1.val + l2.val + add + tmp.next = ListNode.new(cur_val % 10) + tmp = tmp.next + add = cur_val >= 10 ? 1 : 0 + + l1 = l1.next + l2 = l2.next + end + + until l1.nil? + cur_val = l1.val + add + tmp.next = ListNode.new(cur_val % 10) + tmp = tmp.next + add = cur_val >= 10 ? 1 : 0 + l1 = l1.next + end + + until l2.nil? + cur_val = l2.val + add + tmp.next = ListNode.new(cur_val % 10) + tmp = tmp.next + add = l2.val + add >= 10 ? 1 : 0 + l2 = l2.next + end + + tmp.next = ListNode.new(1) if add == 1 + l3 +end \ No newline at end of file