Leetcode 1018. Binary Prefix Divisible By 5
You are given a binary array A
(an array of 0s and 1s).
A binary prefix is any array that can be obtained by removing some (possibly none) elements from the end of the array.
Return a list of boolean
s answer
, where answer[i]
is true if the binary number represented by the prefix A[0] to A[i]
is divisible by 5.
Input: A = [0,1,1]
Output: [true,false,false]
Explanation:
A
contain only 0s and 1s?
A
is a binary array.A
?
A
can be up to 10000
.current_number % 5
), and update this residue as we iterate through the array.current_number = current_number * 2 + A[i]
current_number % 5 = (current_number * 2 + A[i]) % 5
(current_number * 2 + A[i]) % 5
by using modular arithmetic properties.current_number % 5
is 0 at any step, it indicates that the number formed by the current prefix is divisible by 5.import java.util.ArrayList;
import java.util.List;
public class Solution {
public List<Boolean> prefixesDivBy5(int[] A) {
List<Boolean> result = new ArrayList<>();
int currentNumber = 0;
for (int bit : A) {
currentNumber = (currentNumber * 2 + bit) % 5;
result.add(currentNumber == 0);
}
return result;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] A = {0, 1, 1};
System.out.println(sol.prefixesDivBy5(A)); // [true, false, false]
}
}
n
is the length of array A
. Each element is processed once.answer
.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?