Leetcode—2749. 得到整数零需要执行的最少操作数【中等】(__builtin_popcountl)

2025每日刷题(231)

Leetcode---2749. 得到整数零需要执行的最少操作数

实现代码

cpp 复制代码
class Solution {
public:
    int makeTheIntegerZero(int num1, int num2) {
        for(long opt = 0; opt <= 60; ++opt) {
            const long target = num1 - num2 * opt;
            // __builtin_popcountl(target) 返回 target 的 汉明重量,即 target 二进制表示中 1 的个数。
            // target 不能是负数(否则已经把 num1 减过头了);
            // 用恰好 ops 个 2^i 相加得到 target 时,必须有 target 至少为 ops,因为每个 2^i ≥ 1,ops 个这样的数相加的最小和是 ops(全取 2^0 = 1)。
            /*
            若只检查 popcount(target) <= ops 而不检查 ops <= target:
比如 target = 1, ops = 2。
popcount(1) = 1 <= 2 成立,但不可能用两项正的 2^i 凑出 1(最小也得是 1+1=2)。ops <= target 能正确排除这类情况。

若 target < 0:
明显无解(已经把 num1 减过头了)。ops <= target 也会直接判假(因为 ops >= 0),从而排除负数情况。*/
            if(__builtin_popcountl(target) <= opt && target >= opt) {
                return opt;
            }
        }
        return -1;
    }
};

运行结果

之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

相关推荐
WBluuue几秒前
Codeforces 1088 Div1+2(ABC1C2DEF)
c++·算法
中屹指纹浏览器8 分钟前
2026指纹浏览器性能优化实战:多环境并发与资源占用管控技术
经验分享·笔记
蓝色的杯子9 分钟前
Python面试30分钟突击掌握-LeetCode3-Linked list
python·leetcode·面试
像素猎人10 分钟前
map<数据类型,数据类型> mp和unordered_map<数据类型,数据类型> ump的讲解,蓝桥杯OJ4567最大数目
c++·算法·蓝桥杯·stl·map
Narrastory11 分钟前
Note:强化学习(一)
人工智能·算法·强化学习
沐雪轻挽萤22 分钟前
1. C++17新特性-序章
java·c++·算法
郝学胜-神的一滴31 分钟前
从链表到二叉树:树形结构的入门与核心性质解析
数据结构·c++·python·算法·链表
csdn_aspnet37 分钟前
C语言 (QuickSort using Random Pivoting)使用随机枢轴的快速排序
c语言·算法·排序算法
玖釉-37 分钟前
深入解析 meshoptimizer:基于 meshopt_computeSphereBounds 的层级包围球构建与 DAG 优化
c++·算法·图形渲染
CoderMeijun38 分钟前
C++ 单例模式:饿汉模式与懒汉模式
c++·单例模式·设计模式·饿汉模式·懒汉模式