how to find leftmost 1-bit in C++ ?↵
↵
in other word I want to find biggest k so that 2^k <= N for some given number N↵
↵
for example if N=10 then k=3↵
↵
I want an O(1) time and memory solution and also without using built-in functions that may not compile in ALL C++ compilers.↵
↵
thank you in advance.↵
↵
plz tell me this is correct or not ?↵
↵
-------------------------------------------↵
int highestOneBit(int i) {↵
i |= (i >> 1);↵
i |= (i >> 2);↵
i |= (i >> 4);↵
i |= (i >> 8);↵
i |= (i >> 16);↵
return i — (i >> 1);↵
}
↵
in other word I want to find biggest k so that 2^k <= N for some given number N↵
↵
for example if N=10 then k=3↵
↵
I want an O(1) time and memory solution and also without using built-in functions that may not compile in ALL C++ compilers.↵
↵
thank you in advance.↵
↵
plz tell me this is correct or not ?↵
↵
-------------------------------------------↵
int highestOneBit(int i) {↵
i |= (i >> 1);↵
i |= (i >> 2);↵
i |= (i >> 4);↵
i |= (i >> 8);↵
i |= (i >> 16);↵
return i — (i >> 1);↵
}