Propagate the most-significant 1 to all lower positions by repeated OR with right-shifted versions of N. After propagation the number becomes 2*x - 1 where x is the desired power of two; compute (propagated + 1) >> 1 to get x.
classSolution {
public:unsignedint largestPower(unsignedint n) {
if (n ==0) return0ULL;
unsignedint x = n;
x |= x >>1;
x |= x >>2;
x |= x >>4;
x |= x >>8;
x |= x >>16;
x |= x >>32; // covers up to 64-bit
return (x +1ULL) >>1;
}
};
classSolution {
publicintlargestPower(int n) {
if (n == 0) return 0;
int x = n;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
x |= x >> 32;
return (x + 1) >> 1;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
deflargestPower(self, n: int) -> int:
if n ==0:
return0 x = n
x |= x >>1 x |= x >>2 x |= x >>4 x |= x >>8 x |= x >>16 x |= x >>32return (x +1) >>1
classSolution {
public:unsignedint largestPower(unsignedint n) {
if (n ==0) return0ULL;
int idx =31- __builtin_clz(n); // index of MSB (0-based) for 32-bit
return1U<< idx;
}
};