Last active
February 26, 2025 20:34
-
-
Save ludndev/64a576d815f47f68f6d20daad2437777 to your computer and use it in GitHub Desktop.
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 <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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Test it here: https://www.programiz.com/online-compiler/6BTnyB8EfFwvZ