2021-03-06 21:16:43 +01:00
|
|
|
# Convert a given decimal number into binary.
|
|
|
|
|
|
|
|
#
|
|
|
|
# Approach 1: Iterative
|
|
|
|
#
|
2021-03-06 19:08:28 +01:00
|
|
|
|
|
|
|
def decimal_to_binary(n)
|
2021-03-06 21:16:43 +01:00
|
|
|
bin = []
|
|
|
|
|
2021-03-06 19:08:28 +01:00
|
|
|
until n.zero?
|
|
|
|
bin << n % 2
|
2021-03-06 21:16:43 +01:00
|
|
|
n /= 2
|
2021-03-06 19:08:28 +01:00
|
|
|
end
|
2021-03-06 21:16:43 +01:00
|
|
|
|
2021-03-06 20:48:27 +01:00
|
|
|
bin.reverse.join
|
2021-03-06 19:08:28 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
puts 'Binary value of 4 is ' + decimal_to_binary(4).to_s
|
|
|
|
# Binary value of 4 is 100
|
2021-03-06 21:16:43 +01:00
|
|
|
|
|
|
|
puts 'Binary value of 31 is ' + decimal_to_binary(31).to_s
|
|
|
|
# Binary value of 31 is 11111
|
|
|
|
|
|
|
|
puts 'Binary value of 64 is ' + decimal_to_binary(64).to_s
|
|
|
|
# Binary value of 64 is 1000000
|
|
|
|
|
|
|
|
#
|
|
|
|
# Approach 2: Recursive
|
|
|
|
#
|
|
|
|
|
|
|
|
def decimal_to_binary(d)
|
|
|
|
binary = (d % 2).to_s
|
|
|
|
|
2021-03-06 21:29:31 +01:00
|
|
|
return binary if d == 0
|
|
|
|
return 1.to_s if d == 1
|
|
|
|
|
2021-03-10 04:03:25 +01:00
|
|
|
decimal_to_binary(d / 2).to_s + binary
|
2021-03-06 21:16:43 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
puts 'Binary value of 4 is ' + decimal_to_binary(4).to_s
|
|
|
|
# Binary value of 4 is 100
|
|
|
|
|
2021-03-06 19:08:28 +01:00
|
|
|
puts 'Binary value of 31 is ' + decimal_to_binary(31).to_s
|
|
|
|
# Binary value of 31 is 11111
|
2021-03-06 21:16:43 +01:00
|
|
|
|
2021-03-06 19:08:28 +01:00
|
|
|
puts 'Binary value of 64 is ' + decimal_to_binary(64).to_s
|
|
|
|
# Binary value of 64 is 1000000
|