LeetCode 题解工作台

可被 5 整除的二进制前缀

给定一个二进制数组 nums ( 索引从0开始 )。 我们将 x i 定义为其二进制表示形式为子数组 nums[0..i] (从最高有效位到最低有效位)。 例如,如果 nums =[1,0,1] ,那么 x 0 = 1 , x 1 = 2 , 和 x 2 = 5 。 返回布尔值列表 answer ,…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·结合·位运算·操作

bolt

答案摘要

我们用一个变量 来表示当前的二进制前缀,然后遍历数组 ,对于每个元素 ,我们将 左移一位,然后加上 ,再对 取模,判断是否等于 ,如果等于 ,则说明当前的二进制前缀可以被 整除,我们将 加入答案数组,否则将 加入答案数组。 时间复杂度 ,忽略答案数组的空间消耗,空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·结合·位运算·操作 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个二进制数组 nums索引从0开始 )。

我们将xi 定义为其二进制表示形式为子数组 nums[0..i] (从最高有效位到最低有效位)。

  • 例如,如果 nums =[1,0,1] ,那么 x0 = 1x1 = 2, 和 x2 = 5

返回布尔值列表 answer,只有当 xi 可以被 5 整除时,答案 answer[i] 为 true,否则为 false

 

示例 1:

输入:nums = [0,1,1]
输出:[true,false,false]
解释:
输入数字为 0, 01, 011;也就是十进制中的 0, 1, 3 。只有第一个数可以被 5 整除,因此 answer[0] 为 true 。

示例 2:

输入:nums = [1,1,1]
输出:[false,false,false]

 

提示:

  • 1 <= nums.length <= 105 
  • nums[i] 仅为 0 或 1
lightbulb

解题思路

方法一:模拟

我们用一个变量 xx 来表示当前的二进制前缀,然后遍历数组 numsnums,对于每个元素 vv,我们将 xx 左移一位,然后加上 vv,再对 55 取模,判断是否等于 00,如果等于 00,则说明当前的二进制前缀可以被 55 整除,我们将 true\textit{true} 加入答案数组,否则将 false\textit{false} 加入答案数组。

时间复杂度 O(n)O(n),忽略答案数组的空间消耗,空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
class Solution:
    def prefixesDivBy5(self, nums: List[int]) -> List[bool]:
        ans = []
        x = 0
        for v in nums:
            x = (x << 1 | v) % 5
            ans.append(x == 0)
        return ans
speed

复杂度分析

指标
时间complexity is O(n) as we iterate through the array once. Space complexity is O(n) for the answer array; extra space is O(1) since only the current modulo is tracked. Large arrays are handled efficiently due to modulo arithmetic and bit shift updates.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Focus on the binary-to-decimal conversion via prefix computation.

  • question_mark

    Look for constant space optimization using modulo rather than full number storage.

  • question_mark

    Expect clarity in handling edge cases like leading zeros and small arrays.

warning

常见陷阱

外企场景
  • error

    Attempting to convert each prefix to decimal directly, causing overflow.

  • error

    Ignoring modulo arithmetic, resulting in incorrect divisibility checks.

  • error

    Misinterpreting the binary order and updating prefixes incorrectly.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Check divisibility by other numbers like 3 or 7 instead of 5 using the same prefix technique.

  • arrow_right_alt

    Compute sums of binary prefixes rather than divisibility flags.

  • arrow_right_alt

    Return indices of prefixes divisible by 5 instead of boolean array.

help

常见问题

外企场景

可被 5 整除的二进制前缀题解:数组·结合·位运算·操作 | LeetCode #1018 简单