From e692fcce956e4fd3dc2d84be9b9a87c3a5506d2e Mon Sep 17 00:00:00 2001 From: Ting-Yi Liu <46391352+ichbinorange@users.noreply.github.com> Date: Tue, 15 Sep 2020 16:24:42 -0700 Subject: [PATCH 1/2] add binary_to_decimal method and decimal_to_binary method --- lib/binary_to_decimal.rb | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/lib/binary_to_decimal.rb b/lib/binary_to_decimal.rb index 439e8c6..cced3f3 100644 --- a/lib/binary_to_decimal.rb +++ b/lib/binary_to_decimal.rb @@ -4,6 +4,32 @@ # 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. + +# Binary to Decimal def binary_to_decimal(binary_array) - raise NotImplementedError + array_length = binary_array.length + num = 0 + index = 0 + while array_length > 0 + num += binary_array[index].to_i * 2 ** (array_length - 1) + array_length -= 1 + index += 1 + end + return num end + +### Decimal to Binary +# def decimal_to_binary(test_array) +# test_array.each do |user_number| +# quotient_i = user_number.divmod(2)[0] +# modulus_i = Array(user_number.divmod(2)[1]) +# until quotient_i == 0 +# modulus_i.unshift(quotient_i.divmod(2)[1]) +# quotient_i = quotient_i.divmod(2)[0] +# end +# puts "For #{ user_number }, its binary number is \"#{ modulus_i.join }\"" +# end +# end + +# decimal_to_binary([255, 456, 9]) + From bc6768d78f0e06a350ff9122fba96befa40702e9 Mon Sep 17 00:00:00 2001 From: Ting-Yi Liu <46391352+ichbinorange@users.noreply.github.com> Date: Tue, 15 Sep 2020 16:38:11 -0700 Subject: [PATCH 2/2] add binary_to_decimal method and decimal_to_binary method --- lib/binary_to_decimal.rb | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/lib/binary_to_decimal.rb b/lib/binary_to_decimal.rb index cced3f3..5b98108 100644 --- a/lib/binary_to_decimal.rb +++ b/lib/binary_to_decimal.rb @@ -19,17 +19,16 @@ def binary_to_decimal(binary_array) end ### Decimal to Binary -# def decimal_to_binary(test_array) -# test_array.each do |user_number| -# quotient_i = user_number.divmod(2)[0] -# modulus_i = Array(user_number.divmod(2)[1]) -# until quotient_i == 0 -# modulus_i.unshift(quotient_i.divmod(2)[1]) -# quotient_i = quotient_i.divmod(2)[0] -# end -# puts "For #{ user_number }, its binary number is \"#{ modulus_i.join }\"" +# def decimal_to_binary(number_base_ten) +# quotient = number_base_ten.divmod(2)[0] +# modulus = Array(number_base_ten.divmod(2)[1]) +# until quotient == 0 +# modulus.unshift(quotient.divmod(2)[1]) +# quotient = quotient.divmod(2)[0] # end +# return "For #{ number_base_ten }, its binary number is \"#{ modulus.join }\"" # end -# decimal_to_binary([255, 456, 9]) - +# puts decimal_to_binary(255) +# puts decimal_to_binary(456) +# puts decimal_to_binary(9)