#include <iostream>
#include <stdexcept>
#include <cassert>
using namespace std;
unsigned long long closest_int_same_bits(unsigned long long x) {
for (int i = 0; i < 63; i++) {
if (((x >> i) & 1) != ((x >> (i + 1)) & 1)) {
x ^= (1ULL << i) | (1ULL << (i + 1));
return x;
}
}
throw invalid_argument("all bits are 0 or 1");
}
int count_bits_set_to_1(unsigned long long x) {
int count = 0;
while (x) {
x &= (x - 1);
count++;
}
return count;
}
int main(int argc, char *argv[]) {
srand(time(nullptr));
unsigned long long n;
if (argc == 2) {
n = atol(argv[1]);
} else {
n = rand();
}
try {
unsigned long long m = closest_int_same_bits(n);
assert(count_bits_set_to_1(m) == count_bits_set_to_1(n));
cout << n << ' ' << m << endl;
} catch (exception &e) {
cout << n << ' ' << e.what() << endl;
}
return 0;
}
EPI 5.4 CLOSEST INTEGERS WITH THE SAME WEIGHT
最新推荐文章于 2023-12-19 16:08:48 发布