878927. Binary to Decimal
Binary to Decimal
Summary
The problem "Binary to Decimal" involves converting a binary number represented as a string into its decimal equivalent. This problem requires understanding the concept of base conversion and implementing an algorithm to achieve this.
Detailed Explanation
To solve this problem, we need to understand that each digit in a binary number can have two values: 0 or 1. We can convert these binary digits to their corresponding decimal values (0 or 1) and then add them together to get the final decimal value.
Here's a step-by-step breakdown of the solution:
- Initialize an empty string
decimalto store the decimal equivalent. - Iterate through each character in the input binary string from right to left.
- For each character, check if it is '0' or '1'. If it is '0', add 0 to the
decimalstring. If it is '1', add 2^i (where i is the current position of the character) to thedecimalstring. - Continue this process until all characters in the binary string have been processed.
- Return the final decimal equivalent.
Time complexity: O(n), where n is the length of the input binary string, as we are iterating through each character once.
Space complexity: O(1), as we are using a constant amount of space to store the decimal string and other variables.
Optimized Solutions
Java
public int binaryToDecimal(String binary) {
int decimal = 0;
for (int i = binary.length() - 1; i >= 0; i--) {
if (binary.charAt(i) == '1') {
decimal += (int) Math.pow(2, i);
}
}
return decimal;
}