给定一个数组,每次操作可以选择一个或多个元素,减去 2的n次,最少需要多少次操作才能将所有元素变为 0?
比如数组 1 2 3 4
第一次将后三个减掉2 得到1 0 1 2
然后第二次 将1 0 1 2减掉1得到 0 0 0 1
再将1减掉1得到 0 0 0 0,操作3次使所有元素变为0
https://labuladong.online/algo/frequency-interview/bitwise-operation/


重点:所有数求或,看结果二进制1的个数,就是最小操作个数
#include <iostream>
#include <vector>
using namespace std;
int minOperationsToZero(vector<int>& nums) {
int combined = 0;
for (int num : nums) {
combined |= num; // 按位或操作
}
int res = 0;
while(combined != 0){
//因为combined & (combined - 1) 可以消除最后一个 1,
//所以可以用一个循环不停地消除 1 同时计数,直到 combined变成 0 为止。
combined = combined & (combined - 1);
res++;
}
return res;
}
int main() {
vector<int> nums = {1, 2, 3, 4};
cout << "Minimum operations: " << minOperationsToZero(nums) << endl;
return 0;
}
浙公网安备 33010602011771号