当前位置: 首页 > 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] * 30res = infdef calc(bits):return sum(1 << i for i in range(30) if bits[i] > 0)left = 0for right in range(n):for i in range(30):bits[i] += (nums[right] >> i) & 1while left <= right and calc(bits) >= k:res = min(res, right - left + 1)for i in range(30):bits[i] -= (nums[left] >> i) & 1left += 1return -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 = 0while n:res[i] += n & 1n >>= 1i = i ^ 1return 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 = 1Iteration 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 = 0Iteration 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 = 1Iteration 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.lryc.cn/news/540450.html

相关文章:

  • SpringBoot3.x整合WebSocket
  • 猿大师办公助手对比其他WebOffice在线编辑Office插件有什么优势
  • STM32创建静态库lib
  • Hive JOIN过滤条件位置玄学:ON vs WHERE的量子纠缠
  • MAC快速本地部署Deepseek (win也可以)
  • javaEE-13.spring MVC
  • C/C++ | 每日一练 (2)
  • Nginx 常用命令和部署详解及案例示范
  • GO大模型应用开发框架-
  • 保姆级!springboot访问Ollama API并调用DeepSeek模型 Api
  • 力扣hot100 ——搜索二维矩阵 || m+n复杂度优化解法
  • 娱乐使用,可以生成转账、图片、聊天等对话内容
  • 【PyQt5】python可视化开发:PyQt5介绍,开发环境搭建快速入门
  • 使用 FFmpeg 剪辑视频指南
  • AWS云从业者认证题库 AWS Cloud Practitioner
  • 高性能内存对象缓存Memcached详细实验操作
  • 【C++复习专题】—— 类和对象,包含类的引入、访问限定符、类的6个默认成员函数等
  • Three.js 快速入门教程【一】开启你的 3D Web 开发之旅
  • Windows 图形显示驱动开发-CPU 内存调节和64KB 页面支持
  • PLC通信交互系统技术分享
  • ceph HEALTH_WARN clock skew detected on mon.f, mon.o, mon.p, mon.q
  • Git命令行入门
  • pdf-extract-kit paddle paddleocr pdf2markdown.py(效果不佳)
  • Android 10.0 移除wifi功能及相关菜单
  • 什么是Dubbo?Dubbo框架知识点,面试题总结
  • Django+Vue3全栈开发实战:从零搭建博客系统
  • 双重差分学习笔记
  • python组备赛笔记(基础篇)
  • 从零开始构建一个小型字符级语言模型的完整详细教程(基于Transformer架构)
  • XUnity.AutoTranslator-Gemini——调用Google的Gemini API, 实现Unity游戏中日文文本的自动翻译