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

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]

http://www.kler.cn/a/559250.html

相关文章:

  • python~http的请求参数中携带map
  • Python基于flask的智慧交通可视化,大数据智慧交通数据可视化系统
  • 前后端项目部署服务器(传统部署和Docker部署)
  • 计算机毕业设计SpringBoot+Vue.js服装商城 服装购物系统(源码+LW文档+PPT+讲解+开题报告)
  • 解决jupyter notebook不是内部或外部命令问题
  • 近地面无人机遥感:如何利用高光谱数据反演植被生理参数?
  • Arm 将自己制造芯片
  • 改BUG:远程连接redis失败,可能是防火墙的问题
  • vue3中Watch和WatchEffect的用法和区别
  • 大语言模型中的 Token如何理解?
  • 基于 go-wrk 在 Windows 环境下对 Go Web 应用进行 HTTP 压力测试
  • 近10年气象分析(深度学习)
  • 演示基于FPGA的视频图像去雾处理效果
  • 蓝桥杯之阶段考核
  • DeepSeek 助力 Vue 开发:打造丝滑的单选按钮(Radio Button)
  • 国产超强开源大语言模型 DeepSeek-R1-70B 一键部署教程
  • 20250223下载并制作RTX2080Ti显卡的显存的测试工具mats
  • Go语言中使用viper绑定结构体和yaml文件信息时,标签的使用
  • API接口设计模式:从分层架构到CQRS的实战应用
  • Springboot 高频面试题