mirror of
https://github.com/TheAlgorithms/Ruby
synced 2024-12-26 21:58:56 +01:00
Add recursive approach
This commit is contained in:
parent
ff716d1f4c
commit
cef59e1094
1 changed files with 38 additions and 3 deletions
|
@ -1,17 +1,52 @@
|
|||
# Iterative method to convert a given decimal number into binary.
|
||||
# Convert a given decimal number into binary.
|
||||
|
||||
#
|
||||
# Approach 1: Iterative
|
||||
#
|
||||
|
||||
def decimal_to_binary(n)
|
||||
bin = []
|
||||
bin = []
|
||||
|
||||
until n.zero?
|
||||
bin << n % 2
|
||||
n = n / 2
|
||||
n /= 2
|
||||
end
|
||||
|
||||
bin.reverse.join
|
||||
end
|
||||
|
||||
puts 'Binary value of 4 is ' + decimal_to_binary(4).to_s
|
||||
# Binary value of 4 is 100
|
||||
|
||||
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
|
||||
|
||||
if d == 0
|
||||
return binary
|
||||
elsif d == 1
|
||||
return 1.to_s
|
||||
else
|
||||
binary += decimal_to_binary(d / 2).to_s
|
||||
end
|
||||
|
||||
binary.to_i
|
||||
end
|
||||
|
||||
puts 'Binary value of 4 is ' + decimal_to_binary(4).to_s
|
||||
# Binary value of 4 is 100
|
||||
|
||||
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
|
||||
|
|
Loading…
Reference in a new issue