iterative method to convert decimal to binary

This commit is contained in:
Abhinav Anand 2021-03-06 23:38:28 +05:30 committed by GitHub
parent 06ce984675
commit 1fb0258c8e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -0,0 +1,17 @@
# Iterative method to convert a given decimal number into binary.
def decimal_to_binary(n)
bin = []
until n.zero?
bin << n % 2
n = n / 2
end
return 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