Menu
CoddyTech

Binary to Decimal

You get a string s that writes a non-negative number in binary, using only the characters 0 and 1. Return the value of that number as an ordinary integer. The string has no leading zeros, except for the number zero, which is the single character 0.

Function

toDecimal(s: string) → integer
sstring
the binary digits of the number
Returnsinteger
the value of s as an integer

Constraints

  • 1 ≤ s.length ≤ 31
  • s contains only 0 and 1.
  • s starts with 1, unless s is "0".
  • Read the digits yourself instead of calling a built-in base conversion.

Examples

Input
s = "1101"
Output
13
Explanation
Reading from the right, the places are worth 1, 2, 4 and 8. 1101 has 1s in the places for 8, 4 and 1, and 8 + 4 + 1 = 13.

lock icon+16 hidden tests on Submit

challenge icon

Follow-up

Can you read a number written in any base from 2 to 16 with the same loop, where the letters a to f stand for the digits 10 to 15?

Reset code
def toDecimal(s):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

s = "1101"

Expected

13