- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
Advertisements