1-bit and 2-bit Characters
Problem
We have two special characters:
- The first character can be represented by one bit
0
. - The second character can be represented by two bits (
10
or11
).
Given a binary array bits
that ends with 0
, return true
if the last character must be a one-bit character.
Constraints
1 <= bits.length <= 1000
bits[i]
is either0
or1
.
Solution
The problem 1-bit and 2-bit Characters
can be solved by checking indexes for each characters. When the index of the last character matches the last bit, then the last character must be a one-bit character.
Implementation
static const int fast_io = []()
{
std::ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
return 0;
}();
class Solution
{
public:
bool isOneBitCharacter(vector<int> &bits)
{
int idx = 0;
while (idx < bits.size() - 1)
idx += bits[idx] ? 2 : 1;
return idx == bits.size() - 1;
}
};