In this tutorial, we will learn how to convert a decimal number to binary using recursion in Go. We will cover the basic concept of binary numbers and implement a recursive function to perform the conversion.
Binary conversion is the process of converting a decimal (base-10) number to a binary (base-2) number. In binary, numbers are represented using only 0s and 1s.
The syntax to convert a decimal number to binary using recursion in Go is:
func decimalToBinary(n int) string {
if n == 0 {
return "0"
}
if n == 1 {
return "1"
}
return decimalToBinary(n/2) + fmt.Sprintf("%d", n%2)
}
We can create a recursive function to convert a given decimal number to binary by dividing the number by 2 and keeping track of the remainders.
For example,
decimalToBinary
that takes one parameter n
of type int
.n
is 0. If true, return '0'.n
is 1. If true, return '1'.decimalToBinary(n/2)
concatenated with the remainder of n%2
as a string.decimalToBinary
function with a sample number and print the result.package main
import (
"fmt"
)
func decimalToBinary(n int) string {
if n == 0 {
return "0"
}
if n == 1 {
return "1"
}
return decimalToBinary(n/2) + fmt.Sprintf("%d", n%2)
}
func main() {
// Convert 10 to binary
result := decimalToBinary(10)
// Print the result
fmt.Printf("Binary representation of 10 is %s\n", result)
}
Binary representation of 10 is 1010