Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions lib/binary_to_decimal.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,44 @@
# Calculate and return the decimal value for this binary number using
# the algorithm you devised in class.
def binary_to_decimal(binary_array)
power_num = 0
index = -1
decimal_array = []
decimal_number = 0

binary_array.each do |num|
sum_of_nums = binary_array[index] * (2 ** power_num)
power_num += 1
index -= 1

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clever going backwards through the array.


decimal_array << sum_of_nums
end

decimal_array.each do |num|

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: You could use .sum here or have been summing each sum_of_nums in the loop above.

decimal_number += num
end
return decimal_number
raise NotImplementedError
end

def decimal_to_binary(decimal_number)
binary_array = []
reversed_array = []
index = -1

until decimal_number == 0
if decimal_number % 2 == 0
reversed_array << 0
else
reversed_array << 1
end
decimal_number /= 2
end

reversed_array.each do |num|
nums = reversed_array[index]
index -= 1
binary_array << nums
end
return binary_array
end
23 changes: 20 additions & 3 deletions test/binary_to_decimal_test.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
require 'minitest/autorun'
require 'minitest/reporters'
require_relative '../lib/binary_to_decimal'
require "minitest/autorun"
require "minitest/reporters"
require_relative "../lib/binary_to_decimal"

describe "binary to decimal" do
it "From 10011001 to 153" do
Expand Down Expand Up @@ -31,3 +31,20 @@
binary_to_decimal(binary_array).must_equal expected_decimal
end
end
describe "decimal to binary" do
it "Converts from 23 to 10111" do
decimal_number = 23
expected_bin_array = [1, 0, 1, 1, 1]
decimal_to_binary(decimal_number).must_equal expected_bin_array
end
it "Converts from 108 to 1101100" do
decimal_number = 108
expected_bin_array = [1, 1, 0, 1, 1, 0, 0]
decimal_to_binary(decimal_number).must_equal expected_bin_array
end
it "Converts from 1116 to 10001011100" do
decimal_number = 1116
expected_bin_array = [1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0]
decimal_to_binary(decimal_number).must_equal expected_bin_array
end
end