Decimal to Binary Conversion

Problem Link : Decimal to Binary Conversion


Problem: Convert Decimal to Binary

Problem Statement

Given an integer n, return its binary representation as a string.

You are to convert a decimal (base-10) number into its binary (base-2) equivalent.

Examples

Example 1:
Input: n = 7
Output: "111"
Explanation: Binary of 7 is 111

Example 2:
Input: n = 33
Output: "100001"
Explanation: Binary of 33 is 100001


Intuition

To convert a decimal number to binary, we repeatedly divide the number by 2 and collect the remainders. The binary number is formed by reading the remainders in reverse order.

For example, converting 33:

Reading remainders in reverse: 100001


Approach

  1. Use a loop to divide the number by 2 until it becomes 0.

  2. At each step, append the remainder (n % 2) to a StringBuilder.

  3. After the loop, reverse the string to get the correct binary representation.


Code (Java)

class Solution {
    static String decToBinary(int n) {
        StringBuilder sb = new StringBuilder();
        while (n > 0) {
            int r = n % 2;
            sb.append(r);
            n /= 2;
        }
        return sb.reverse().toString();
    }
}

Time and Space Complexity


Dry Run

Input: n = 7

Step n n % 2 Resulting StringBuilder
1 7 1 "1"
2 3 1 "11"
3 1 1 "111"
0 loop ends

Reverse "111" → Output: "111"


Conclusion

This problem is a straightforward implementation of decimal to binary conversion using repeated division and modulus. It’s an essential fundamental operation in computer science and is efficiently solved using basic control structures.