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:
-
33 ÷ 2 = 16, remainder = 1
-
16 ÷ 2 = 8, remainder = 0
-
8 ÷ 2 = 4, remainder = 0
-
4 ÷ 2 = 2, remainder = 0
-
2 ÷ 2 = 1, remainder = 0
-
1 ÷ 2 = 0, remainder = 1
Reading remainders in reverse: 100001
Approach
-
Use a loop to divide the number by 2 until it becomes 0.
-
At each step, append the remainder (
n % 2) to aStringBuilder. -
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
-
Time Complexity: O(log2n)
Because we divide the number by 2 in each iteration. -
Space Complexity: O(log2n)
For storing the binary digits in theStringBuilder.
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.