
Problem
Solution
Submissions
Decimal to Binary Number
Certification: Basic Level
Accuracy: 50%
Submissions: 4
Points: 10
Write a C++ program that converts a decimal (base-10) number to its binary (base-2) representation.
Example 1
- Input: n = 10
- Output: "1010"
- Explanation:
- Step 1: Initialize an empty string to store the binary representation.
- Step 2: Repeatedly divide the decimal number by 2 and collect the remainders.
- Step 3: The remainders, read from bottom to top, give the binary representation.
- Step 4: For 10, the divisions and remainders are: 10÷2=5 remainder 0, 5÷2=2 remainder 1, 2÷2=1 remainder 0, 1÷2=0 remainder 1.
Example 2
- Input: n = 23
- Output: "10111"
- Explanation:
- Step 1: Initialize an empty string to store the binary representation.
- Step 2: Repeatedly divide the decimal number by 2 and collect the remainders.
- Step 3: The remainders, read from bottom to top, give the binary representation.
- Step 4: For 23, the divisions and remainders are: 23÷2=11 remainder 1, 11÷2=5 remainder 1, 5÷2=2 remainder 1, 2÷2=1 remainder 0, 1÷2=0 remainder 1.
Constraints
- 0 ≤ n ≤ 10^9
- Input is a non-negative integer
- Time Complexity: O(log n)
- Space Complexity: O(log n)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use the division and remainder method: repeatedly divide by 2 and collect the remainders
- The binary digits should be read in reverse order
- Handle the special case of input 0 separately
- Consider using a string to build the binary representation