[LeetCode] 1018. Binary Prefix Divisible By 5 Binary Prefix Divisible By 5 (Easy) (JAVA) One question per day

[LeetCode] 1018. Binary Prefix Divisible By 5 Binary Prefix Divisible By 5 (Easy) (JAVA)

Title address: https://leetcode.com/problems/binary-prefix-divisible-by-5/

Title description:

Given an array A of 0s and 1s, consider N_i: the i-th subarray from A[0] to A[i] interpreted as a binary number (from most-significant-bit to least-significant-bit.)

Return a list of booleans answer, where answer[i] is true if and only if N_i is divisible by 5.

Example 1:

Input: [0,1,1]
Output: [true,false,false]
Explanation: 
The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10.  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]

Note:

  • 1 <= A.length <= 30000
  • A[i] is 0 or 1

General idea

Given an array A consisting of a number of 0s and 1s. 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.

Problem-solving method

  1. It is to calculate whether the binary number formed by the first n bits can be divisible by 5
  2. I already know the result pre of the first n digits, and now there are n + 1 digits more, how to find the result? That is, the first n bits are uniformly shifted to the left by one place, then pre << 1, plus the result of A[n + 1]
  3. Note: In order to prevent the int from exceeding the limit, it is necessary to take the remainder of the calculated result pre: pre% 5
class Solution {
    public List<Boolean> prefixesDivBy5(int[] A) {
        List<Boolean> res = new ArrayList<>();
        int pre = 0;
        for (int i = 0; i < A.length; i++) {
            pre <<= 1;
            pre += A[i];
            pre = pre % 5;
            res.add(pre == 0);
        }
        return res;
    }
}

Execution time: 4 ms, beating 92.76% of Java users
Memory consumption: 39.2 MB, beating 41.06% of Java users

Welcome to pay attention to my official account, LeetCode updates one question every day

Guess you like

Origin blog.csdn.net/qq_16927853/article/details/112599125