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
23 changes: 21 additions & 2 deletions lib/binary_to_decimal.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,25 @@
# 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
def binary_to_decimal(arr)
# Creating a blank new array the size of the original array
reversed = Array.new(arr.length)
# Starting decimal value at 0
decimal = 0
# Setting i to the last index of the array
i = arr.length - 1
arr.each do |number|
# Adding numbers to reversed aray
# Starting at end of original array
reversed[i] = number
# Decreasing value of i
i -= 1
end

# Going through each index of the reversed array
reversed.each_index do |index|
# If number is not 0, add 2 ** index to decimal
decimal += 2 ** index if reversed[index] != 0
end
return decimal
end