300. Bits in a Chain

A row of 30 light switches is wired as a chain of nodes. Each node holds either 0 (off) or 1 (on), and the first node is the most significant bit of a binary number, while the last node is the least significant bit.

Given the head of the chain, return the integer value of the binary number it spells. Leading zeros are allowed and do not change the value; for example the chain 0, 1, 1 means 3. The chain has at least one node and at most 30 nodes, so the answer always fits in a 32-bit signed integer.

Example 1

Input:
head = [1,0,1,1,0,1]
Output:
45
Explanation:

The bits 101101 equal 32 + 8 + 4 + 1 = 45.

Example 2

Input:
head = [0,0,1,1,1]
Output:
7
Explanation:

Leading zeros are ignored: 00111 equals 7.

Constraints

1 ≤ chain length ≤ 30
Each node value is 0 or 1
The first node is the most significant bit.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…