diff --git a/lib/binary_to_decimal.rb b/lib/binary_to_decimal.rb index 439e8c6..f1edc80 100644 --- a/lib/binary_to_decimal.rb +++ b/lib/binary_to_decimal.rb @@ -4,6 +4,29 @@ # 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. + +# first way to do it taking out reverse +# def binary_to_decimal(binary_array) +# decimal = 0 +# count = 7 +# +# binary_array.each do |num| +# decimal += (num * (2**count)) +# count -= 1 +# end +# +# return decimal +# end + +# Using times loop and count + def binary_to_decimal(binary_array) - raise NotImplementedError + decimal = 0 + count = binary_array.length + + count.times do |index| + decimal += (binary_array[index] * (2**(count-1-index))) + end + + return decimal end diff --git a/specs/binary_to_decimal_spec.rb b/specs/binary_to_decimal_spec.rb index ba17713..521fa9f 100644 --- a/specs/binary_to_decimal_spec.rb +++ b/specs/binary_to_decimal_spec.rb @@ -1,5 +1,6 @@ require 'minitest/autorun' require 'minitest/reporters' +require 'minitest/pride' require_relative '../lib/binary_to_decimal' describe "binary to decimal" do