Convert Decimal to Binary using Recursion in Go
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.
What is Binary 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.
Syntax
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)
}
Example 1: Converting a decimal number to binary using recursion
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,
- Define a function named
decimalToBinary
that takes one parametern
of typeint
. - Check if
n
is 0. If true, return '0'. - Check if
n
is 1. If true, return '1'. - Return the result of
decimalToBinary(n/2)
concatenated with the remainder ofn%2
as a string. - In the main function, call the
decimalToBinary
function with a sample number and print the result.
Go Program
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)
}
Output
Binary representation of 10 is 1010