diff options
author | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
---|---|---|
committer | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
commit | d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch) | |
tree | 96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /power_of_four.c | |
download | leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip |
initial
Diffstat (limited to 'power_of_four.c')
-rw-r--r-- | power_of_four.c | 28 |
1 files changed, 28 insertions, 0 deletions
diff --git a/power_of_four.c b/power_of_four.c new file mode 100644 index 0000000..7ab3cae --- /dev/null +++ b/power_of_four.c @@ -0,0 +1,28 @@ +// 342. Power of Four +#include <stdbool.h> +#include <stdio.h> + +/* + * given an integer 'n', return 'true' if it is a power of four, otherwise, + * return 'false'. an integer 'n' is a power of four if there exists an integer + * 'x' such that 'n == 4^x' + */ + +bool isPowerOfFour(int n) { + int ans = 0, pos = 1, ones = 0; + while (n) { + if (n & 1) { // if 'n' is even... + ans++; + ones = pos; + } + n >>= 1; // 'n' / 2 + pos++; + } + return ans == 1 && ones & 1; +} + +int main() { + printf("%d\n", isPowerOfFour(16)); // expect: 1 + printf("%d\n", isPowerOfFour(5)); // expect: 0 + printf("%d\n", isPowerOfFour(1)); // expect: 1 +} |