Given an array A consisting of a number of 0s and 1. 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, the 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 The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Idea: I finally have a simple question, just hit it hard.
class Solution {
public List<Boolean> prefixesDivBy5(int[] A) {
List<Boolean> res = new ArrayList<Boolean>();
int len = A.length;
int mark = 0;
for(int i=0;i<len;i++)
{
mark = ((mark*2)%5 +A[i])%5;
if(mark==0) {
res.add(true);
}else{
res.add(false);
}
}
return res;
}
}