Created
March 18, 2012 01:47
-
-
Save keyvan/2067682 to your computer and use it in GitHub Desktop.
Find if an integer is a power of 2 in C without libraries
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
The below code is an efficient function to find if an integer number is a power of 2 in C without using any libraries. It would be good to think why it's efficient. | |
int IsPowerOfTwo(int x) { | |
while (((x % 2) == 0) && x > 1) /* While x is even and > 1 */ | |
x /= 2; | |
return (x == 1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
As a follower on Twitter pointed out (@mshonle), a better way is to use bit operations that I never thought about. I was drown in short-circuiting the conditional branch in there!
The code can be simplified like this:
return (x & (x - 1) == 0);