From fbfa1232b24dda28dd486fedce1c1c5986d6c4c4 Mon Sep 17 00:00:00 2001 From: Victoria Garcia Date: Sun, 25 Feb 2018 22:56:39 -0800 Subject: [PATCH] Here's my binary-to-decimal conversion method. --- lib/binary_to_decimal.rb | 10 +++++++++- specs/binary_to_decimal_spec.rb | 6 ++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/lib/binary_to_decimal.rb b/lib/binary_to_decimal.rb index 439e8c6..3a8430b 100644 --- a/lib/binary_to_decimal.rb +++ b/lib/binary_to_decimal.rb @@ -5,5 +5,13 @@ # 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 + decimal_value = 0 + # Note: The input array has to be reversed in order for the + # algorithm I devised in class to work. + binary_array.reverse! + binary_array.each_with_index do |bit, index| + bit_value = bit * (2 ** index) + decimal_value = decimal_value + bit_value + end + return decimal_value end diff --git a/specs/binary_to_decimal_spec.rb b/specs/binary_to_decimal_spec.rb index ba17713..dd062c0 100644 --- a/specs/binary_to_decimal_spec.rb +++ b/specs/binary_to_decimal_spec.rb @@ -2,6 +2,12 @@ require 'minitest/reporters' require_relative '../lib/binary_to_decimal' +# Edited this to allow use of mintest reporters. Made no other +# edits. + +Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new + + describe "binary to decimal" do it "From 10011001 to 153" do binary_array = [1, 0, 0, 1, 1, 0, 0, 1]