231. Power of Two

problem description

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

Example 1:

Input: 1
Output: true 
Explanation: 2^0 = 1

Example 2:

Input: 16
Output: true
Explanation: 2^4 = 16

Example 3:

Input: 218
Output: false

algorithm thought

这里有种解法是一直除二,但是还可以利用LeetCode的漏洞。

LeetCode检测一个题的答案是一直调用这个函数,如果再函数里声明一个static变量,那么,就只会初始化一次。之后直接返回即可。用在这题最好不过

code

class Solution {
public:
    bool isPowerOfTwo(int n) {
        static unordered_set<int> se{1<<0,1<<1,1<<2,1<<3,1<<4,1<<5,1<<6,1<<7,1<<8,1<<9,
                                     1<<10,1<<11,1<<12,1<<13,1<<14,1<<15,1<<16,1<<17,1<<18,1<<19,
                                     1<<20,1<<21,1<<22,1<<23,1<<24,1<<25,1<<26,1<<27,1<<28,1<<29,
                                     1<<30};
        return se.count(n);
    }
};

algorithm analysis

不难看出,这里时间和空间都是复杂度O(1)

Last updated