Created
April 4, 2015 02:12
-
-
Save rmccullagh/f740b33e1ba19210b07f to your computer and use it in GitHub Desktop.
is_power_of_two
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
| #include <stdbool.h> | |
| #include <stdio.h> | |
| bool is_power_of_two(size_t); | |
| int my_pop_count(size_t); | |
| int main() | |
| { | |
| size_t n = 8; | |
| if(is_power_of_two(n)) { | |
| fprintf(stdout, "%zu is a power of 2\n", n); | |
| } else { | |
| fprintf(stdout, "%zu is not a power of 2\n", n); | |
| } | |
| return 0; | |
| } | |
| bool is_power_of_two(size_t x) | |
| { | |
| return my_pop_count(x) > 1 ? false : true; | |
| } | |
| /* | |
| * return the Hamming Weight | |
| * | |
| * IS_POWER_OF_2(x) my_pop_count(x) > 1 ? false : true | |
| */ | |
| int my_pop_count(size_t x) | |
| { | |
| unsigned setBits = 0; | |
| do { | |
| int rem = x % 2; | |
| if(rem == 1) { | |
| setBits++; | |
| } | |
| x = x / 2; | |
| } while(x != 0); | |
| return setBits; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment