VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-decimal-binary-conversion/

⇱ Decimal to Binary Conversion Program - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Decimal to Binary Conversion Program

Last Updated : 14 Jul, 2025

Given a non negative number n, the task is to convert the given number into an equivalent binary representation.

Examples:

Input: n = 12
Output: "1100"
Explanation: the binary representation of 12 is "1100", since 12 = 1×23 + 1×22 + 0×21+ 0×20 = 12

Input: n = 33
Output: "100001"
Explanation: the binary representation of 33 is "100001", since 1×25 + 0×24 + 0×23 + 0×22 + 0×21 + 1×20 = 33

[Approach - 1] Division by 2 - O(log₂(n)) Time and O(log₂(n)) Space

To convert a decimal number to binary, repeatedly divide it by 2 and record the remainders. Reading these remainders in reverse gives the binary representation.


Output
1100

[Approach - 2] Using Head Recursion - O(log₂(n)) Time and O(log₂(n)) Space

The idea is same as the previous approach, but we will use recursion to generate the binary equivalent number.


Output
1100

[Approach - 3] Using Bitwise Operators - O(log₂(n)) Time and O(log₂(n)) Space

Using bitwise operators, we can extract binary digits by checking the least significant bit (n & 1) and then right-shifting the number (n >> 1) to process the next bit.
This method is faster than arithmetic division and modulo, as bitwise operations are more efficient at the hardware level.


Output
1100

[Approach - 4] Using Built-in Methods - O(log₂(n)) Time and O(log₂(n)) Space

The main idea is to leverage built-in functions provided by programming languages to directly convert a decimal number to its binary form. These functions abstract away the underlying logic and return the binary representation as a string, making the process quick, concise, and error-free.


Output
1100
Comment