1. 程式人生 > >Leetcode 231 Power of Two

Leetcode 231 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

這個題目考察的為位運算,題目要求寫一個函式來判斷是不是二的冪,主要有兩種方法:

1)

/*
將整數和其相反數相與,效果即為只留下最左邊的一,如果為二的冪則字串中只有一個1,如果不是的話就有多個1
*/
class Solution {
    public boolean isPowerOfTwo(int n) {
        return n > 0 && (n & -n) == n;
    }
}

2)

/*
這個方法為將最大的數相餘n,如果n為二的冪的話,那麼相餘之後必定為0,即可以判斷
/*
class Solution {
public:
    bool isPowerOfTwo(int n) {
        return n > 0 && (1 << 30) % n == 0;
    }
};