位运算

1、__builtin_popcount 的使用

1.1 1的数量

#include <bits/stdc++.h>

using namespace std;
using i64 = long long;

void solve() {
	int x;
	cin >> x;
	int t = __builtin_popcount(x);
	if (t <= 2) {
		for (int i = x + 1; ; i++) {
			if (__builtin_popcount(i) <= 2) {
				cout << i << "\n";
				break;
			}
		}
	} else {
		cout << t << "\n";
	}
}

int main() {
	ios::sync_with_stdio(false), cin.tie(nullptr);
	int t;
	cin >> t;
	while (t--) {
		solve();
	}
	return 0;
}

1.2 3011. 判断一个数组是否可以变为有序

class Solution {
public:
    bool canSortArray(vector<int>& nums) {
        int n = nums.size();
        for (int i = 0; i < n; ) {
            int cnt = __builtin_popcount(nums[i]);
            int s = i;
            i++;
            while (i < n && __builtin_popcount(nums[i]) == cnt) i++;
            sort(nums.begin() + s, nums.begin() + i);
        }
        if (is_sorted(nums.begin(), nums.end())) return true;
        return false;
    }
};
posted @ 2024-07-13 10:53  胖柚の工作室  阅读(14)  评论(0)    收藏  举报