878928. Decimal to binary
Easy
Decimal to Binary
Slug: decimal-to-binary-1610434291--161808
Difficulty: Easy
Id: 878928
Topic Tags: CPP
Summary
The problem involves converting a given decimal number into its binary representation. This is a basic algorithmic problem that requires understanding of the concept of binary numbers and their conversion from decimal.
Detailed Explanation
To convert a decimal number to binary, we can use the fact that each digit in binary represents 2^0 (1) or 2^1 (2), and so on. We iterate through the given decimal number, for each digit:
- If the current digit is less than 2, the corresponding binary bit will be a 0.
- If the current digit is greater than or equal to 2, we take the remainder of the division by 2, which gives us the next binary bit. We then subtract this remainder from the decimal number and repeat the process until the decimal number becomes 0.
Here's a step-by-step breakdown:
- Initialize an empty string
binaryto store the resulting binary representation. - Iterate through each digit of the given decimal number.
- For each digit, if it is less than 2, append '0' to
binary. - If the digit is greater than or equal to 2, calculate its remainder when divided by 2 and append this remainder (either 0 or 1) to
binary. Then subtract this remainder from the decimal number. - Repeat steps 3-4 until the decimal number becomes 0.
- Return the resulting binary representation stored in
binary.
Time complexity: O(log n), where n is the given decimal number, as we are performing log(n) operations (division and subtraction). Space complexity: O(1), as we are using a constant amount of space to store the binary representation.
Optimized Solutions
Java
public String decimalToBinary(int n) {
StringBuilder binary = new StringBuilder();
while (n > 0) {
int remainder = n % 2;
n /= 2;
binary.append(remainder == 0 ? '0' : '1');
}
return binary.toString();
}