Write a Golang program to convert a decimal number to its binary form


Examples

  • Input decimal_num = 13 => Output = 8+4+1 => 1101
  • Input decimal_num = 11 => Output = 8+2+1 => 1011

Approach to solve this problem

  • Step 1: Define a function that accepts a decimal number, decimal_num, type is int.
  • Step 2: Define an array to store the remainder while dividing decimal number by 2.
  • Step 3: Start a for loop until the decimal number becomes 0.
  • Step 4: Print the binary array in reverse order.

Program

Live Demo

package main
import (
   "fmt"
)

func decimalToBinary(num int){
   var binary []int

   for num !=0 {
      binary = append(binary, num%2)
      num = num / 2
   }
   if len(binary)==0{
      fmt.Printf("%d\n", 0)
   } else {
      for i:=len(binary)-1; i>=0; i--{
         fmt.Printf("%d", binary[i])
      }
      fmt.Println()
   }
}

func main() {
   decimalToBinary(87)
   decimalToBinary(10)
   decimalToBinary(31)
   decimalToBinary(0)
}

Output

1010111
1010
11111
0

Updated on: 04-Feb-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements