[LeetCode] 1018. Binary Prefix Divisible By 5 可被5整除的二进制前缀
Given an array A
of 0
s and 1
s, consider N_i
: the i-th subarray from A[0]
to A[i]
interpreted as a binary number (from most-significant-bit to least-significant-bit.)
Return a list of booleans answer
, where answer[i]
is true
if and only if N_i
is divisible by 5.
Example 1:
Input: [0,1,1]
Output: [true,false,false]
Explanation:
The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10. 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]
Note:
1 <= A.length <= 30000
A[i]
is0
or1
这道题给了一个只由0和1组成的数组,问从0开始每个子数组表示的二进制数是否可以整除5,二进制数是从高位到低位的。既然是一道 Easy 的题目,也就不用太多的技巧,直接按顺序遍历即可。首先对于第一个数字,可以快速知道其是否可以整除5,当子数组新加一位,实际上相当于之前的数字左移了一位,也就相当于乘以了2,所以新的子数组表示的数字就是之前的数字乘以2再加上新加进来的数字,然后就可以判断是否可以整除5了。但是需要注意的一点是,由于A数组可能会很长,所以最终累加出来的数字可能会很大,超过整型最大值,甚至也超过长整型的最大值,为了避免这种情况,对每次累加出来的新数字都对5取余,这样就不会溢出了,参见代码如下:
class Solution {
public:
vector<bool> prefixesDivBy5(vector<int>& A) {
vector<bool> res;
int cur = 0, n = A.size();
for (int i = 0; i < n; ++i) {
cur = (cur * 2 + A[i]) % 5;
res.push_back(cur % 5 == 0);
}
return res;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/1018
参考资料:
https://leetcode.com/problems/binary-prefix-divisible-by-5/