Skip to content

1018. Binary Prefix Divisible By 5

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  vector<bool> prefixesDivBy5(vector<int>& nums) {
    vector<bool> ans;
    int curr = 0;

    for (const int num : nums) {
      curr = (curr * 2 + num) % 5;
      ans.push_back(curr % 5 == 0);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
  public List<Boolean> prefixesDivBy5(int[] nums) {
    List<Boolean> ans = new ArrayList<>();
    int curr = 0;

    for (final int num : nums) {
      curr = (curr * 2 + num) % 5;
      ans.add(curr % 5 == 0);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def prefixesDivBy5(self, nums: list[int]) -> list[bool]:
    ans = []
    curr = 0

    for num in nums:
      curr = (curr * 2 + num) % 5
      ans.append(curr % 5 == 0)

    return ans