Skip to content

Instantly share code, notes, and snippets.

@bparanj
Created August 20, 2020 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bparanj/39b215cb285426f19eeb369cee675226 to your computer and use it in GitHub Desktop.
Save bparanj/39b215cb285426f19eeb369cee675226 to your computer and use it in GitHub Desktop.
# 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} head
# @return {Integer}
def get_decimal_value(head)
numbers = []
current = head
while current
numbers << current.val
current = current.next
end
size = numbers.size
total = 0
numbers.each do |n|
break if size == 0
total = total + (2 ** (size-1) * n)
size -= 1
end
total
end
@bparanj
Copy link
Author

bparanj commented Aug 20, 2020

Refactored solution:

def get_decimal_value(head)
    numbers = []
    current = head
    while current
       numbers << current.val 
       current = current.next
    end
    
    size = numbers.size 
    total = 0
    numbers.each do |item|
      total = total + (2 ** (size-1) * item)
      size -= 1
    end
    total
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment