#include <iostream>
#include <cmath>
unsigned int roundToNearestPowerOf2(unsigned int n) {
if (n <= 0) {
return 0;
}
int nextPowerOf2 = pow(2, ceil(log2(n))); // 64 (num = 37)
int prevPowerOf2 = pow(2, floor(log2(n))); // 32 (num = 37)
// Check which power of 2 is closest to n
int diff1 = nextPowerOf2 - n;
int diff2 = n - prevPowerOf2;
if (diff1 <= diff2) {
return nextPowerOf2;
}
else {
return prevPowerOf2;
}
}
int main() {
unsigned int num = 37;
std::cout << "Nearest power of 2: " << roundToNearestPowerOf2(num) << std::endl;
}
/*
run:
Nearest power of 2: 32
*/