From binary to a number
- O(n) · Medium
- Full plan
- Python
- JavaScript
- strings
- loops
Problem
In binary there are only zeros and ones, and every position is worth twice as much as the one to its right: 1, 2, 4, 8, 16, 32...
Write a function that takes a string of zeros and ones and returns the number it stands for. With "1010" the answer is 10, because it is 8 + 0 + 2 + 0.
There is a comfortable road: go through the string from left to right and, on each character, double what you have so far and add 1 if that character is a one. When the string ends you already have the number.
Leading zeros are harmless: "0011" is 3 as well.
If the string holds anything else (a 2, a letter, a space) it is not a binary number: in that case you return -1. The empty string is not a number either, so it returns -1 too.
Examples
The one from the example
"1010" → 10
A single one
"1" → 1
Two ones make three
"11" → 3
Five digits
"11010" → 26
A long one
"10001101000" → 1128
Leading zeros
"00011111" → 31
A digit sneaked in the middle
"1021" → -1
Letters stuck at the end
"10cats" → -1
A space in the middle
"101 010" → -1
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def binary_to_number(text):
passJavaScript
function binaryToNumber(text) {
}It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.