LeetCode - Algorithms - 231. Power of Two

Problem

231. Power of Two

Java

1

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

Submission Detail

  • 1108 / 1108 test cases passed.
  • Runtime: 1 ms, faster than 100.00% of Java online submissions for Power of Two.
  • Memory Usage: 36.8 MB, less than 52.24% of Java online submissions for Power of Two.

binary logarithm

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

Submission Detail

  • 1108 / 1108 test cases passed.
  • Runtime: 2 ms, faster than 38.56% of Java online submissions for Power of Two.
  • Memory Usage: 38.7 MB, less than 6.14% of Java online submissions for Power of Two.

bit magic

© java bit magic

1
2
3
4
5
6
7
class Solution {
public boolean isPowerOfTwo(int n) {
if (n < 1)
return false;
return (n & (n - 1)) == 0;
}
}

Submission Detail

  • 1108 / 1108 test cases passed.
  • Runtime: 1 ms, faster than 100.00% of Java online submissions for Power of Two.
  • Memory Usage: 38.5 MB, less than 11.61% of Java online submissions for Power of Two.

Integer Limitations

1
2
3
4
5
class Solution {
public boolean isPowerOfTwo(int n) {
return n > 0 && 1073741824 % n == 0;
}
}

Submission Detail

  • 1108 / 1108 test cases passed.
  • Runtime: 2 ms, faster than 38.65% of Java online submissions for Power of Two.
  • Memory Usage: 38.9 MB, less than 5.09% of Java online submissions for Power of Two.