LeetCode - 231. Power of Two

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

Example 1:

Input: 16
Output: true

Example 2:

Input: 5
Output: false
判断一个数是否为2的次幂,偶然发现3年前做这道题就是很简单的循环对2取余整除。顺手用位运算写了一行代码又提交了一次。效率提升了200多倍。
public boolean isPowerOfTwo(int n) {
    return n > 0 && (n & (n - 1)) == 0;
}

原理参考这篇博客的技巧部分。

 

posted @ 2018-12-02 16:27  Pickle  阅读(184)  评论(0编辑  收藏  举报