878927. Binary to Decimal

Easy

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:

  1. Initialize an empty string decimal to store the decimal equivalent.
  2. Iterate through each character in the input binary string from right to left.
  3. For each character, check if it is '0' or '1'. If it is '0', add 0 to the decimal string. If it is '1', add 2^i (where i is the current position of the character) to the decimal string.
  4. Continue this process until all characters in the binary string have been processed.
  5. 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

View on GeeksforGeeks
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;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.