Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Basics

Binary to Decimal

Easy · Basics · Asked at TCS, Infosys, Wipro, Accenture, Cognizant

Convert the binary number to decimal and print it.

Input

A single line with the binary number (no leading zeros unless it is 0).

Output

The decimal value.

Constraints

Read the bits left to right: value = value × 2 + bit. With up to 62 bits the value needs a 64-bit integer.

Example 1

Input

1011

Output

11

Example 2

Input

0

Output

0

Hints

  1. Reading left to right, each new bit doubles what you have and adds itself.
  2. Up to 62 bits fit in a signed 64-bit integer.

Approach

Start from 0 and for every character do value = value × 2 + (bit). This is Horner's rule for base 2 — no powers of two are needed.

Complexity: O(length) time · O(1) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    string s;
    cin >> s;
    long long v = 0;
    for (char c : s) v = v * 2 + (c - '0');
    cout << v << "\n";
    return 0;
}

Python solution

s = input().strip()
v = 0
for c in s:
    v = v * 2 + (c == "1")
print(v)

Java solution

import java.util.*;

public class Main {
    public static void main(String[] args) {
        String s = new Scanner(System.in).next();
        long v = 0;
        for (char c : s.toCharArray()) v = v * 2 + (c - '0');
        System.out.println(v);
    }
}

Solve Binary to Decimal online · All practice problems