From fafb7b19c19f4b1fb90fb35eb1ef4bec0305295d Mon Sep 17 00:00:00 2001 From: Amanda Ungco Date: Wed, 22 Aug 2018 21:27:04 -0700 Subject: [PATCH 1/2] created binary to decimal method --- lib/binary_to_decimal.rb | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/lib/binary_to_decimal.rb b/lib/binary_to_decimal.rb index 439e8c6..9c6c98f 100644 --- a/lib/binary_to_decimal.rb +++ b/lib/binary_to_decimal.rb @@ -4,6 +4,17 @@ # 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(binary_number) + binary_number_array = binary_number.split('') + decimal = 0 + j = 7 + binary_number_array.each do |digit| + product = digit.to_i * (2**j) + j -= 1 + decimal = decimal.to_i + product.to_i + end + return decimal end + + +p binary_to_decimal('11110100') From 3e81a7f5b71a45dcf04928e7e2e2dce9e8318d15 Mon Sep 17 00:00:00 2001 From: Amanda Ungco Date: Wed, 22 Aug 2018 22:30:29 -0700 Subject: [PATCH 2/2] ran tests and changed parameter to accept an array instead of a string --- lib/binary_to_decimal.rb | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/lib/binary_to_decimal.rb b/lib/binary_to_decimal.rb index 9c6c98f..56ae6fe 100644 --- a/lib/binary_to_decimal.rb +++ b/lib/binary_to_decimal.rb @@ -4,17 +4,14 @@ # 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_number) - binary_number_array = binary_number.split('') +def binary_to_decimal(binary_array) + # binary_number_array = binary_number.split('') decimal = 0 j = 7 - binary_number_array.each do |digit| + binary_array.each do |digit| product = digit.to_i * (2**j) j -= 1 decimal = decimal.to_i + product.to_i end return decimal end - - -p binary_to_decimal('11110100')