Problem Statement
Convert a decimal number to binary number.
Examples
Example 1:
Input: number = 13
Output: 1101
Explanation:
Decimal Number: 13
13 / 2 = 6 (Remainder = 1)
6 / 2 = 3 (Remainder = 0)
3 / 2 = 1 (Remainder = 1)
1 / 2 = 0 (Remainder = 1)
Binary Equivalent: 1101
Theory
- Decimal System: The decimal system is a base-10 numeral system, which uses 10 symbols (0-9) to represent numbers.
- Binary System: The binary system is a base-2 numeral system, which uses only two symbols (0 and 1) to represent numbers.
Different Approaches
Approach 1: Using Division
Step 1: 13 / 2 = 6 (Remainder = 1)
|
V
1
Step 2: 6 / 2 = 3 (Remainder = 0)
|
V
0
Step 3: 3 / 2 = 1 (Remainder = 1)
|
V
1
Step 4: 1 / 2 = 0 (Remainder = 1)
|
V
1
Now append them in reverse order.
Binary Equivalent: 1101
#include <iostream>
#include <string>
using namespace std;
// Function to convert decimal to binary using division method
string decimalToBinaryDivision(int n) {
string binary = ""; // Initialize an empty string to store binary digits
// Divide the decimal number by 2 until quotient is 0
while (n > 0) {
int rem = n % 2; // Calculate remainder
binary = to_string(rem) + binary; // Store the remainder
n /= 2; // Update the quotient
}
return binary; // Return the binary equivalent
}
int main() {
int decimal = 13;
string binary = decimalToBinary(decimal);
cout << "Binary equivalent of " << decimal << " is " << binary << endl;
return 0;
}
Output:
Binary equivalent of 13 is 1101
Complexity Analysis
Time Complexity:O(log n)
Space Complexity:O(log n)
2 Approach 2: Using Bitwise Shift Operator
In this approach, we use the bitwise shift operator to convert the decimal number to binary.
Code Implementation in C++:
#include <iostream>
using namespace std;
// Function to convert decimal to binary using bitwise shift operator method
string decimalToBinaryBitwise(int n) {
string binary = ""; // Initialize an empty string to store binary digits
// Loop through each bit from left to right (from most significant to least significant)
for (int i = 31; i >= 0; i--) {
// Check if the bit at position i is set (1) or not (0)
if (n & (1 << i))
binary += "1"; // If set, append '1' to the binary string
else
binary += "0"; // If not set, append '0' to the binary string
}
return binary; // Return the binary equivalent
}
int main() {
int decimal = 13;
// Convert decimal to binary using bitwise shift operator method
string binary_bitwise = decimalToBinaryBitwise(decimal);
cout << "Binary equivalent of " << decimal << " using bitwise shift operator method: " << binary_bitwise << endl;
}
Output:
Binary equivalent of 13 is 00000000000000000000000000001101
Complexity Analysis:
Time Complexity:O(1)
Space Complexity:O(1)