LeetCode——1018.可被5整除的二进制前缀

class Solution:
    def prefixesDivBy5(self, A: List[int]) -> List[bool]:
        if not A:
            return []
        res = []
        pre = 0
        #使用位运算更方便一些,使用的内存也较少,程序的执行效率也比较高
        for digit in A:
            pre = (pre<<1)+digit
            res.append(not pre%5)

        return res


        res = []
        num = ''
        for digit in A:
            num += str(digit)
            if int(num,2)%5==0:
                res.append(True)
            else:
                res.append(False)
        
        return res
  • 暴力解决
    • 前缀和然后计算最终的数
  • 位运算 
    • 利用位运算,计算下一个数的是时候,将当前数字左移,然后加上遍历的数字即可

猜你喜欢

转载自blog.csdn.net/weixin_37724529/article/details/112602147