Member-only story
Here’s a Ruby method to convert a decimal number to binary without any in-built methods.
def decimal_to_binary(decimal_number)
return '0' if decimal_number == 0
binary = ''
while decimal_number > 0
binary = (decimal_number % 2).to_s + binary
decimal_number /= 2
end
return binary
end
# Output
puts decimal_to_binary(10) # Output: "1010"
puts decimal_to_binary(42) # Output: "101010"
puts decimal_to_binary(255) # Output: "11111111"
Let’s go through the implementation line by line and explain what each line does using a detailed example,
def decimal_to_binary(decimal_number)
return '0' if decimal_number == 0
In this line, we define a method called decimal_to_binary
that takes a decimal_number
as input. If the decimal_number
is equal to 0, we return the string '0' because the binary representation of 0 is simply '0'.
binary = ''
We initialize an empty string called binary
. This variable will store the binary representation of the decimal_number
.
while decimal_number > 0
We enter a while
loop that will continue as long as the decimal_number
is greater than 0. This loop will help us extract the binary digits from the decimal number.