From 912b7fc4ced149aa1b14335acf39769b7ac0b1a1 Mon Sep 17 00:00:00 2001 From: Cassandra Archibald Date: Sun, 19 Aug 2018 09:08:08 -0700 Subject: [PATCH] Completed binary to decimal --- lib/binary_to_decimal.rb | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/lib/binary_to_decimal.rb b/lib/binary_to_decimal.rb index 439e8c6..5da4bcb 100644 --- a/lib/binary_to_decimal.rb +++ b/lib/binary_to_decimal.rb @@ -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