Leetcode—2749. 得到整数零需要执行的最少操作数【中等】(__builtin_popcountl)
2025每日刷题(231)
Leetcode—2749. 得到整数零需要执行的最少操作数
实现代码
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;}
};
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!