Binary to Decimal

easy Number Problems

Problem

Read a binary number (only the characters 0 and 1) and print its decimal value. Example: 1010 is 10.

Constraints

  • 1 <= length of text <= 62

Examples

Input

1010

Output

10

Solutions

Best approachTime O(d)Space O(1)

Each new bit doubles what we have read so far and adds the new bit. This method (Horner's method) needs no powers of 2.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Convert a binary number to decimal.
 * Input   : One text made of the digits 0 and 1.
 * Output  : The decimal value.
 * Approach: Read the bits from left to right: result = result * 2 + bit.
 * Time    : O(d)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        String bits = new Scanner(System.in).next();

        // Step 1: The result starts at 0.
        long result = 0;

        // Step 2: Read the bits from left to right.
        for (int index = 0; index < bits.length(); index++) {
            // Step 3: Turn the character into a number. The character '1' minus the character '0' is the number 1.
            int bit = bits.charAt(index) - '0';

            // Step 4: Multiply the result by 2 and add the bit. Example: 10 -> 10 * 2 + 1 = 101.
            result = result * 2 + bit;
        }

        // Step 5: Print the decimal value.
        System.out.println(result);
    }
}
Hints (1)
  1. What happens to the value of 101 if you add a 0 at the end?