
Problem
Solution
Submissions
Decimal Number to Binary
Certification: Basic Level
Accuracy: 75%
Submissions: 4
Points: 5
Write a C# program to implement the DecimalToBinary(int number) function, which converts a decimal (base-10) integer to its binary (base-2) representation as a string.
Algorithm
- Step 1: Handle the special case of number = 0, which should return "0".
- Step 2: For negative numbers, decide whether to use two's complement or include a negative sign.
- Step 3: For positive numbers, repeatedly divide the number by 2 and collect the remainders.
- Step 4: Reverse the collected remainders to form the binary representation.
Example 1
- Input: number = 10
- Output: "1010"
- Explanation:
- 10 ÷ 2 = 5 remainder 0
- 5 ÷ 2 = 2 remainder 1
- 2 ÷ 2 = 1 remainder 0
- 1 ÷ 2 = 0 remainder 1
- Reading the remainders from bottom to top: 1010
Example 2
- Input: number = -7
- Output: "-111"
- Explanation:
- We take the absolute value: 7
- 7 ÷ 2 = 3 remainder 1
- 3 ÷ 2 = 1 remainder 1
- 1 ÷ 2 = 0 remainder 1
- Reading the remainders from bottom to top: 111
- Adding the negative sign: -111
Constraints
- -2^31 ≤ number ≤ 2^31 - 1
- The output should be a string representation of the binary number.
- Time Complexity: O(log n) where n is the input number
- 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 a string builder or similar structure to efficiently build the binary representation.
- Remember to handle the edge case of 0.
- For negative numbers, either represent with a leading minus sign or implement proper two's complement.
- Consider using built-in methods for validation or comparison.