AC Ruby Solution


  • 0
    S
    def split_sum(sum)
      if sum >= 10
        remainder = sum % 10
        carriage = (sum - remainder) / 10
        sum = remainder
        return {
          carriage: carriage,
          sum: sum
        }
      else
        return {
          carriage: 0,
          sum: sum
        }
      end
    end
    
    
    
    def add_two_numbers(l1, l2)
      node = ListNode.new(0)
      head = node
      carriage = 0
      while(!l1.nil? || !l2.nil? || carriage != 0)
        l1_val = l1 != nil ? l1.val : 0
        l2_val = l2 != nil ? l2.val : 0
        sum = carriage + l1_val + l2_val
        split = split_sum(sum)
        node.next = ListNode.new(split[:sum])
        carriage = split[:carriage]
        node = node.next
        l1 = (l1 == nil) ? l1 : l1.next
        l2 = (l2 == nil) ? l2 : l2.next
      end
      head.next
    end
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.