Using O(1) time to check whether an integer n is a power of 2.

Example

For n=4, return true

For n=5, return false

Challenge

O(1) time

Analysis:

Use bit manipulation. Be carefull about the 0 and negtive integer.

Solution:

 1 class Solution {
 2     /*
 3      * @param n: An integer
 4      * @return: True or false
 5      */
 6     public boolean checkPowerOf2(int n) {
 7         if (n<=0) return false;
 8         boolean res = ((n & (n-1))==0) ? true : false;
 9         return res;
10     }
11 };

 

相关文章:

  • 2021-05-02
  • 2021-08-17
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-03
  • 2021-06-12
  • 2022-12-23
猜你喜欢
  • 2021-11-19
  • 2022-12-23
  • 2022-12-23
  • 2022-02-21
  • 2022-01-04
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案