問題
解いた
# Definition for singly-linked list. # class ListNode # attr_accessor :val, :next # def initialize(val = 0, _next = nil) # @val = val # @next = _next # end # end # @param {ListNode} l1 # @param {ListNode} l2 # @return {ListNode} def get_list(list_node) result = [] result << list_node.val loop do next_node = list_node.next if next_node.nil? break end result << next_node.val list_node = next_node end result end def add_two_numbers(l1, l2) sum_arr = [] l1_list = get_list(l1) l2_list = get_list(l2) move_up_flag = false long_arr = l1_list.length >= l2_list.length ? l1_list : l2_list short_arr = long_arr == l1_list ? l2_list : l1_list long_arr.each_with_index do |long_num, index| short_num = short_arr[index].nil? ? 0 : short_arr[index] sum = long_num + short_num if move_up_flag sum += 1 move_up_flag = false end if sum >= 10 sum -= 10 move_up_flag = true end sum_arr << sum end if move_up_flag sum_arr << 1 end p sum_arr end
結果
うーーん。遅い。