Leetcode - 1018 Binary Prefix Divisible By 5 (Easy)
題目描述:給定一個由 0 和 1 組成的數組,定義 Ni 爲 從 A[0] 到 A[i] 的第 i 個子數組被解釋爲一個二進制數(從最高有效位到最低有效位)。返回布爾值列表 answer,判斷 Ni 是否能夠被 5 整除。
Input: [0,1,1,1,1,1]
Output: [true,false,false,false,true,false]
解題思路:只用 0 - 4 的範圍的餘數表示是否能被 5 整除。
public List<Boolean> prefixesDivBy5(int[] A) {
List<Boolean> result = new ArrayList<>(A.length);
int res = 0;
for (int j = 0, l = A.length; j < l; j++) {
res = (res * 2 + A[j]) % 5;
result.add(res == 0);
}
return result;
}