Leetcode Leetcode 1018. Binary prefix divisible by 5 (python)

Topic:

Given an array A consisting of a number of 0s and 1. 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).
Returns a list of boolean values ​​answer, only when N_i is divisible by 5, the answer[i] is true, otherwise it is false.

Example_1:

Input: [0,1,1]
Output: [true,false,false]
Explanation: The
input numbers are 0, 01, 011; that is, 0, 1, 3 in decimal. 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]

Solution_1:

Convert binary numbers into decimal numbers for remainder judgment

Code_1:

class Solution:
    def prefixesDivBy5(self, A: List[int]) -> List[bool]:
        a = 0
        res = []
        for i in range(len(A)):
            a = a * 2  + A[i]
            if a % 5 == 0:
                res.append(True)
            else:
                res.append(False)
        return res

Result_1:

Insert picture description here

Solution_2:

Perform modulo 5 on a and take the remainder
a = a% 5 to
ensure that the value of a is always controlled at 0~4
to optimize the algorithm,
reduce the use of space and accelerate the speed of operation

Result_2:

Operation efficiency has improved a lot
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_50791900/article/details/112727713