当前位置: 首页 > news >正文

Leetcode 位计算

3095. 或值至少 K 的最短子数组 I

3097. Shortest Subarray With OR at Least K II

class Solution:
    def minimumSubarrayLength(self, nums: List[int], k: int) -> int:
        n = len(nums)
        bits = [0] * 30
        res = inf
        def calc(bits):
            return sum(1 << i for i in range(30) if bits[i] > 0)

        left = 0
        for right in range(n):
            for i in range(30):
                bits[i] += (nums[right] >> i) & 1
            while left <= right and calc(bits) >= k:
                res = min(res, right - left + 1)
                for i in range(30):
                    bits[i] -= (nums[left] >> i) & 1
                left += 1

        return -1 if res == inf else res

2595. Number of Even and Odd Bits

class Solution:
    def evenOddBit(self, n: int) -> List[int]:
        res = [0, 0]
        i = 0
        while n:
            res[i] += n & 1
            n >>= 1
            i = i ^ 1
        return res
  • n >>= 1: Performs a right bitwise shift on n
  • i = i ^ 1: This cleverly toggles the index i between 0 and 1. The ^ operator is the bitwise XOR. Since i is either 0 or 1:
    If i is 0, 0 ^ 1 is 1.
    If i is 1, 1 ^ 1 is 0.
Binary representation of 8: 1000
Iterations:
Iteration 1:
n = 8 (1000)
n & 1 = 1000 & 0001 = 0000 = 0
res[0] = 0 + 0 = 0
n >>= 1 (n becomes 4, which is 0100)
i = 0 ^ 1 = 1

Iteration 2:
n = 4 (0100)
n & 1 = 0100 & 0001 = 0000 = 0
res[1] = 0 + 0 = 0
n >>= 1 (n becomes 2, which is 0010)
i = 1 ^ 1 = 0

Iteration 3:
n = 2 (0010)
n & 1 = 0010 & 0001 = 0000 = 0
res[0] = 0 + 0 = 0
n >>= 1 (n becomes 1, which is 0001)
i = 0 ^ 1 = 1

Iteration 4:
n = 1 (0001)
n & 1 = 0001 & 0001 = 0001 = 1
res[1] = 0 + 1 = 1
n >>= 1 (n becomes 0, which is 0000)
i = 1 ^ 1 = 0
Loop terminates because n is now 0.

Return value:
res = [0, 1]

相关文章:

  • 【算法】------区间问题(贪心)
  • 本地部署DeepSeek大模型
  • ORM框架详解:为什么不直接写SQL?
  • MYSQL的第一次
  • C++中const T为什么少见?它有什么用途?
  • 使用 Docker 部署 Flask 应用
  • 【Android】Android 悬浮窗开发 ( 动态权限请求 | 前台服务和通知 | 悬浮窗创建 )
  • Java反射机制
  • Golang访问Google Sheet
  • Java常见问题(一)
  • 新数据结构(12)——代理
  • python入门笔记5-集合与字典
  • 基于Springboot的公寓报修管理系统【附源码】
  • 环境变量与本地变量
  • 【Python】迭代器与生成器详解(可迭代对象、定义、实现方式、区别、使用场景)
  • ROS 2机器人开发--第一个节点
  • 数据中心储能蓄电池状态监测管理系统 组成架构介绍
  • 网络协议相关知识有哪些?
  • linux进程的内存空间映射(段)
  • Spring Boot 常用注解详解
  • 高璞任中国第一汽车集团有限公司党委常委、副总经理
  • 乌克兰否认俄收复库尔斯克州,称战斗仍在持续
  • “冲刺万亿城市”首季表现如何?温州领跑,大连GDP超徐州
  • 上海虹桥至福建三明直飞航线开通,飞行时间1小时40分
  • 讲座预告|大国博弈与创新破局:如何激励中国企业创新
  • 专访倪军:人要有终身学习能力,一张文凭无法像以往支撑那么多年