
Problem
Solution
Submissions
Convert a Decimal Number to Binary
Certification: Basic Level
Accuracy: 82.86%
Submissions: 35
Points: 5
Write a Python program that converts a decimal number to its binary representation.
Example 1
- Input: number = 10
- Output: "1010"
- Explanation:
- Step 1: Divide 10 by 2, get quotient 5 and remainder 0.
- Step 2: Divide 5 by 2, get quotient 2 and remainder 1.
- Step 3: Divide 2 by 2, get quotient 1 and remainder 0.
- Step 4: Divide 1 by 2, get quotient 0 and remainder 1.
- Step 5: Reading the remainders from bottom to top gives us "1010".
Example 2
- Input: number = 33
- Output: "100001"
- Explanation:
- Step 1: Divide 33 by 2, get quotient 16 and remainder 1.
- Step 2: Divide 16 by 2, get quotient 8 and remainder 0.
- Step 3: Divide 8 by 2, get quotient 4 and remainder 0.
- Step 4: Divide 4 by 2, get quotient 2 and remainder 0.
- Step 5: Divide 2 by 2, get quotient 1 and remainder 0.
- Step 6: Divide 1 by 2, get quotient 0 and remainder 1.
- Step 7: Reading the remainders from bottom to top gives us "100001".
Constraints
- 0 ≤ number ≤ 10^9
- Return the binary representation as a string without the "0b" prefix
- Time Complexity: O(log n), where n is the input number
- Space Complexity: O(log n) to store the binary digits
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 bin() function: bin(number)[2:]
- Use format(): format(number, 'b')
- Iterative division: while number > 0: binary = str(number % 2) + binary; number //= 2
- Use recursion: def to_binary(n): return "" if n == 0 else to_binary(n // 2) + str(n % 2)