description
Given an array A consisting of a number of 0s and 1s. We define N_i: The i-th sub-array from A[0] to A[i] is interpreted as a binary number (from the most significant bit to the least significant bit).
Return a list of boolean values answer, only when N_i is divisible by 5, answer[i] is true, otherwise it is false.
Example 1:
Input: [0,1,1]
Output: [true,false,false]
Explanation: The
input numbers are 0, 01, 011; that is, 0, 1, 3 in decimal. Only the first number is divisible by 5, so answer[0] is true.
Example 2:
Input: [1,1,1]
Output: [false,false,false]
Example 3:
Input: [0,1,1,1,1,1]
Output: [true,false,false,false,true,false]
Example 4:
Input: [1,1,1,0,1]
Output: [false,false,false,false,false]
prompt:
1 <= A.length <= 30000
A[i] 为 0 或 1
Source: LeetCode
Link: https://leetcode-cn.com/problems/binary-prefix-divisible-by-5/
Solve
class Solution {
public:
vector<bool> prefixesDivBy5(vector<int> &A) {
int pre = 0;
vector<bool> res;
for (int index : A) {
pre = (pre * 2 + index) % 10;
res.emplace_back(pre == 3 || pre == 6 || pre ==9);
}
return res;
}
vector<bool> prefixesDivBy3(const vector<int> &A) {
int pre = 0;
vector<bool> res;
for (int index : A) {
pre = (pre * 2 + index) % 3;
res.emplace_back(pre == 0);
}
return res;
}
};