Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion lib/binary_to_decimal.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,15 @@
# The least significant bit is at index 7.
# Calculate and return the decimal value for this binary number using
# the algorithm you devised in class.

def binary_to_decimal(binary_array)
raise NotImplementedError
exponent_array = [2**7, 2**6, 2**5, 2**4, 2**3, 2**2, 2**1, 2**0]

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This works, but you've hardcoded for specific powers of 2. Can you think of a way to make this more flexible?

result_array = []
index = 0
while result_array.length < binary_array.length
(binary_array[index]).zero? ? num_to_add = 0 : num_to_add = binary_array[index] * exponent_array[index]
result_array << num_to_add
index += 1
end
result_array.sum
end