LeetCode #231 - Power of Two - Easy

Problem

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

Example

Input: 2
Output: true

Algorithm

整理一下題意:給定一個整數,判斷其是否是2的冪。

簡單判斷即可。注意特殊情況,如負數,0,1。

代碼如下。

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

        return isp;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章