mirror of
https://github.com/TheAlgorithms/Ruby
synced 2024-12-28 22:24:14 +01:00
Fix merge issues
This commit is contained in:
commit
c2b3b327ac
3 changed files with 50 additions and 18 deletions
|
@ -37,7 +37,7 @@
|
|||
* [Binary To Decimal](https://github.com/TheAlgorithms/Ruby/blob/master/maths/binary_to_decimal.rb)
|
||||
* [Ceil](https://github.com/TheAlgorithms/Ruby/blob/master/maths/ceil.rb)
|
||||
* [Ceil Test](https://github.com/TheAlgorithms/Ruby/blob/master/maths/ceil_test.rb)
|
||||
* [Iterative Decimal To Binary](https://github.com/TheAlgorithms/Ruby/blob/master/maths/iterative_decimal_to_binary.rb)
|
||||
* [Decimal To Binary](https://github.com/TheAlgorithms/Ruby/blob/master/maths/decimal_to_binary.rb)
|
||||
* [Number Of Digits](https://github.com/TheAlgorithms/Ruby/blob/master/maths/number_of_digits.rb)
|
||||
* [Square Root](https://github.com/TheAlgorithms/Ruby/blob/master/maths/square_root.rb)
|
||||
* [Square Root Test](https://github.com/TheAlgorithms/Ruby/blob/master/maths/square_root_test.rb)
|
||||
|
|
49
maths/decimal_to_binary.rb
Normal file
49
maths/decimal_to_binary.rb
Normal file
|
@ -0,0 +1,49 @@
|
|||
# Convert a given decimal number into binary.
|
||||
|
||||
#
|
||||
# Approach 1: Iterative
|
||||
#
|
||||
|
||||
def decimal_to_binary(n)
|
||||
bin = []
|
||||
|
||||
until n.zero?
|
||||
bin << 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
|
||||
|
||||
return binary if d == 0
|
||||
return 1.to_s if d == 1
|
||||
|
||||
binary = decimal_to_binary(d / 2).to_s + binary
|
||||
|
||||
binary
|
||||
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
|
|
@ -1,17 +0,0 @@
|
|||
# Iterative method to convert a given decimal number into binary.
|
||||
|
||||
def decimal_to_binary(n)
|
||||
bin = []
|
||||
until n.zero?
|
||||
bin << 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
|
Loading…
Reference in a new issue