diff options
author | Jack Sangdahl <[email protected]> | 2025-08-09 10:32:45 +0200 |
---|---|---|
committer | Jack Sangdahl <[email protected]> | 2025-08-09 10:32:45 +0200 |
commit | a09548594e7f57c4d6d31964f7c1d99bf2f822b2 (patch) | |
tree | a6cc8cd3c5748428f2b67e65ed88b2217ee87163 | |
parent | f878bb71563de831927bdf52b44e2dcc0ab4c577 (diff) | |
download | leetcode-a09548594e7f57c4d6d31964f7c1d99bf2f822b2.tar.gz leetcode-a09548594e7f57c4d6d31964f7c1d99bf2f822b2.zip |
231. power of two
-rw-r--r-- | power_of_two.c | 6 | ||||
-rw-r--r-- | power_of_two.py | 8 |
2 files changed, 5 insertions, 9 deletions
diff --git a/power_of_two.c b/power_of_two.c index 0be3ced..c22b26f 100644 --- a/power_of_two.c +++ b/power_of_two.c @@ -7,11 +7,7 @@ * that 'n == 2^x' */ -bool isPowerOfTwo(int n) { - if (n <= 0) - return 0; - return !(n & (n - 1)); -} +bool isPowerOfTwo(int n) { return n > 0 && __builtin_popcount(n) == 1; } int main() { printf("%d\n", isPowerOfTwo(1)); // expect: 1 diff --git a/power_of_two.py b/power_of_two.py index 80dd7d0..4d0f73f 100644 --- a/power_of_two.py +++ b/power_of_two.py @@ -1,4 +1,5 @@ # 231. Power of Two +from math import log2 """ given an integer 'n', return true if it is a power of two. otherwise, return @@ -13,10 +14,9 @@ class Solution(object): :type n: int :rtype: bool """ - if n <= 0: - return False - return not (n & (n - 1)) - + return n > 0 and (log2(n) % 1 == 0) + + if __name__ == "__main__": obj = Solution() print(obj.isPowerOfTwo(1)) |