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;
    }
};

运行结果

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

相关推荐
子春一5 小时前
Flutter for OpenHarmony:构建一个 Flutter 四色猜谜游戏,深入解析密码逻辑、反馈算法与经典益智游戏重构
算法·flutter·游戏
方见华Richard5 小时前
世毫九量子原住民教育理念全书
人工智能·经验分享·交互·原型模式·空间计算
MZ_ZXD0015 小时前
springboot旅游信息管理系统-计算机毕业设计源码21675
java·c++·vue.js·spring boot·python·django·php
人道领域5 小时前
AI抢人大战:谁在收割你的红包
大数据·人工智能·算法
TracyCoder1236 小时前
LeetCode Hot100(34/100)——98. 验证二叉搜索树
算法·leetcode
A尘埃6 小时前
电信运营商用户分群与精准运营(K-Means聚类)
算法·kmeans·聚类
A星空1236 小时前
一、Linux嵌入式的I2C驱动开发
linux·c++·驱动开发·i2c
凡人叶枫6 小时前
C++中智能指针详解(Linux实战版)| 彻底解决内存泄漏,新手也能吃透
java·linux·c语言·开发语言·c++·嵌入式开发
power 雀儿6 小时前
掩码(Mask)机制 结合 多头自注意力函数
算法
会叫的恐龙7 小时前
C++ 核心知识点汇总(第六日)(字符串)
c++·算法·字符串