Golang Program to convert an integer into binary representation

Go ProgrammingServer Side ProgrammingProgramming

Examples

For example, n = 1 (Binary Representation of 1: 1)

For example, n = 5 (Binary Representation of 5: 101)

For example, n = 20 (Binary Representation of 5: 10100)

For example, n = 31 (Binary Representation of 31: 11111)

Approach to solve this problem

Step 1 − Define a method that accepts an integer, n.

Step 2 − Convert n into binary representation using golang package

Step 3 − Return the converted binary representation.

Example

 Live Demo

package main
import (
   "fmt"
   "strconv"
)
func IntegerToBinary(n int) string {
   return strconv.FormatInt(int64(n), 2)
}
func main(){
   n := 1
   fmt.Printf("Binary Representation of %d is %s.\n", n, IntegerToBinary(n))
   n = 5
   fmt.Printf("Binary Representation of %d is %s.\n", n, IntegerToBinary(n))
   n = 20
   fmt.Printf("Binary Representation of %d is %s.\n", n, IntegerToBinary(n))
   n = 31
   fmt.Printf("Binary Representation of %d is %s.\n", n, IntegerToBinary(n))
}

Output

Binary Representation of 1 is 1.
Binary Representation of 5 is 101.
Binary Representation of 20 is 10100.
Binary Representation of 31 is 11111.
raja
Published on 18-Mar-2021 05:41:27
Advertisements