From f035e4f04939219d5979f67d9e36b307a60d15fb Mon Sep 17 00:00:00 2001 From: Jack Sangdahl Date: Fri, 15 Aug 2025 08:33:19 +0200 Subject: 342. power of four --- power_of_four.c | 14 ++------------ power_of_four.py | 2 +- 2 files changed, 3 insertions(+), 13 deletions(-) diff --git a/power_of_four.c b/power_of_four.c index 7ab3cae..47f88fe 100644 --- a/power_of_four.c +++ b/power_of_four.c @@ -1,6 +1,5 @@ // 342. Power of Four -#include -#include +#include "leetcode.h" /* * given an integer 'n', return 'true' if it is a power of four, otherwise, @@ -9,16 +8,7 @@ */ 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; + return n > 0 && __builtin_popcount((unsigned)n) == 1 && !((n - 1) % 3); } int main() { diff --git a/power_of_four.py b/power_of_four.py index 13a0dc5..da9ab09 100644 --- a/power_of_four.py +++ b/power_of_four.py @@ -9,7 +9,7 @@ return 'false'. an integer 'n' is a power of four if there exists an integer class Solution(object): def isPowerOfFour(self, n): - return n != 0 and n & (n - 1) == 0 and n & 1431655765 == n + return n > 0 and n.bit_count() == 1 and (n - 1) % 3 == 0 if __name__ == "__main__": -- cgit v1.2.3