LeetCode - Algorithms - 342. Power of Four

Problem

342. Power of Four

Java

1

1
2
3
4
5
6
7
class Solution {
public boolean isPowerOfFour(int num) {
for (; num > 0 && num % 4 == 0; )
num = num >>> 2;
return num == 1;
}
}

Submission Detail

  • 1060 / 1060 test cases passed.
  • Runtime: 1 ms, faster than 100.00% of Java online submissions for Power of Four.
  • Memory Usage: 37 MB, less than 34.15% of Java online submissions for Power of Four.

Logarithm

1
2
3
4
5
6
7
8
class Solution {
public boolean isPowerOfFour(int num) {
if (num < 1)
return false;
Double logbase4 = Math.log(num) / Math.log(4);
return logbase4 - logbase4.intValue() <= 0.00000000000001;
}
}

Submission Detail

  • 1060 / 1060 test cases passed.
  • Runtime: 1 ms, faster than 100.00% of Java online submissions for Power of Four.
  • Memory Usage: 36.9 MB, less than 45.20% of Java online submissions for Power of Four.

bit magic 1

Check if given number is power of 4 or not

1
2
3
4
5
class Solution {
public boolean isPowerOfFour(int num) {
return num != 0 && (num & (num - 1)) == 0 && (num & 0xAAAAAAAA) == 0;
}
}

Submission Detail

  • 1060 / 1060 test cases passed.
  • Runtime: 2 ms, faster than 28.69% of Java online submissions for Power of Four.
  • Memory Usage: 38.6 MB, less than 13.38% of Java online submissions for Power of Four.

bit magic 2

Check if given number is power of 4 or not

1
2
3
4
5
class Solution {
public boolean isPowerOfFour(int num) {
return ((num & (num - 1)) == 0) && (num % 3 == 1);
}
}

Submission Detail

  • 1060 / 1060 test cases passed.
  • Runtime: 1 ms, faster than 100.00% of Java online submissions for Power of Four.
  • Memory Usage: 38.8 MB, less than 8.34% of Java online submissions for Power of Four.