Leetcode之Power of Two

题目:

Given an integer, write a function to determine if it is a power of two.

Example 1:

Input: 1
Output: true 
Explanation: 20 = 1

Example 2:

Input: 16
Output: true
Explanation: 24 = 16

Example 3:

Input: 218
Output: false

代码:

方法一——常规思路,时间复杂度O(logN):

class Solution {
public:
    bool isPowerOfTwo(int n) {
        if(n<=0)return false;
        if(n==1)return true;
        if(n%2!=0)return false;
        return isPowerOfTwo(n/2);
    }
};

方法二——利用位运算的性质,时间复杂度O(1):

class Solution {
public:
    bool isPowerOfTwo(int n) {
        return n>0&&!(n&(n-1));
    }
};

 

Leetcode之Power of TwoLeetcode之Power of Two 一只荣 发布了312 篇原创文章 · 获赞 25 · 访问量 2万+ 私信 关注
上一篇:ocjp 考试题之十


下一篇:908. Smallest Range I