Do bitwise operators like &
(AND) take more runtime than common for
loops?
Today I was doing a power of 2 question in LeetCode. My code was this:
if (n > 0 && (n & (n - 1)) == 0) {
return true;
}
return false;
It gave me a runtime of 5ms. I tried resubmitting to see if there was any variance in runtime but it was the same.
So then I wrote my code using a for
loop:
for (int i = 0; i <= 30; i++){
int ans = pow(2, i);
if (n == ans){
return true;
}
}
return false;
The runtime became 0 ms.
I was hoping for a faster runtime with my bitwise operator code but instead I got the slowest one.
2