Skip to content

Instantly share code, notes, and snippets.

@ludndev
Last active February 26, 2025 20:34
Show Gist options
  • Save ludndev/64a576d815f47f68f6d20daad2437777 to your computer and use it in GitHub Desktop.
Save ludndev/64a576d815f47f68f6d20daad2437777 to your computer and use it in GitHub Desktop.
#include <stdio.h>
// fn to check if a number is a power of 2
int isPowerOfTwo(int n) {
return n > 0 && !(n & (n - 1));
}
int main() {
printf("How to find if a number is a power of 2\n");
int testNumbers[] = {1, 2, 3, 4, 8, 16, 18, 32, 64, 100};
int size = sizeof(testNumbers) / sizeof(testNumbers[0]);
printf("Testing isPowerOfTwo fn :\n\n");
for (int i = 0; i < size; i++) {
int num = testNumbers[i];
printf("%d is %sa power of `2`\n", num, isPowerOfTwo(num) ? "" : "not ");
}
return 0;
}
@ludndev
Copy link
Author

ludndev commented Feb 26, 2025

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment