Binary Prefix Divisible By 5
Problem
You are given a binary array nums
(0-indexed).
We define xi
as the number whose binary representation is the subarray nums[0..i]
(from most-significant-bit to least-significant-bit).
- For example, if
nums = [1,0,1]
, thenx0 = 1
,x1 = 2
, andx2 = 5
.
Return an array of booleans answer
where answer[i]
is true
if xi
is divisible by 5
.
Constraints
1 <= nums.length <= 105
nums[i]
is either0
or1
.
Solution
The problem Binary Prefix Divisible By 5
can be solved by adding each digit into a number and checking each step if the number is divisble by 5. However, as 2100000 - 1
, the largest value xi
can have, is well above the range of integer in C++, we need to find a way to check if xi
is divisble by 5 without directly calculating xi
. xi
can be represented as xi = 5α + β
where α
and β
are non-negative integers and 0 <= β < 5
. Then, xi+1 = 2 * (5α + β) + φ = 10α + 2 * β + φ
where φ = 0, 1
. In this case, it is obvious that subtracting 5α
from xi
does not have any affect on the modulo operation as it does not affect the remainder of xi
or xi+1
. Therefore, by performing modulo 5 operation each step on the sum of digits, it is possible to check if the sum is divisible by 5 while not overflowing the variable.
Implementation
static const int fast_io = []()
{
std::ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
return 0;
}();
class Solution
{
public:
vector<bool> prefixesDivBy5(vector<int> &nums)
{
vector<bool> ret;
int sum = 0;
for (int num : nums)
{
sum = ((sum << 1) + num) % 5;
ret.push_back(!sum);
}
return ret;
}
};