Input: nums =[0,1,1]Output: [true,false,false]Explanation: The input numbers in binary are 0,01,011; which are 0,1, and 3in base-10.Only the first number is divisible by 5, so answer[0]istrue.
We can keep track of the current prefix as a number, but only care about its remainder modulo 5. This is because divisibility by 5 only depends on the remainder, and the number can get very large.
classSolution {
public List<Boolean>prefixesDivBy5(int[] nums) {
List<Boolean> ans =new ArrayList<>();
int cur = 0;
for (int b : nums) {
cur = (cur * 2 + b) % 5;
ans.add(cur == 0);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funprefixesDivBy5(nums: IntArray): List<Boolean> {
val ans = mutableListOf<Boolean>()
var cur = 0for (b in nums) {
cur = (cur * 2 + b) % 5 ans.add(cur ==0)
}
return ans
}
}
1
2
3
4
5
6
7
8
9
from typing import List
classSolution:
defprefixesDivBy5(self, nums: list[int]) -> list[bool]:
ans: list[bool] = []
cur =0for b in nums:
cur = (cur *2+ b) %5 ans.append(cur ==0)
return ans
1
2
3
4
5
6
7
8
9
10
11
impl Solution {
pubfnprefixes_div_by5(nums: Vec<i32>) -> Vec<bool> {
letmut ans = Vec::with_capacity(nums.len());
letmut cur =0;
for b in nums {
cur = (cur *2+ b) %5;
ans.push(cur ==0);
}
ans
}
}