1. 程式人生 > >leetcode-231-Power of Two

leetcode-231-Power of Two

dsm top margin n) line != 都是 ont bottom

Power of Two

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

推斷給出的數,是否為2的次方,如1,2,4,8,16...




移位操作,2的次方的數,換位2進制表示,都是第一個為1 ,其後面都是0,。如8=1000
class Solution {
public:
    bool isPowerOfTwo(int n) {
        if (!n) return false; //等於0的情況
        while (n != 1){       // 二進制第一個數肯定是1,不推斷
            if (n&1)  return false;  // 為1  則不是2的次方
            n = n >> 1;
        }
        return true;  
    }
};




利用 n&(n - 1) 。即將二進制的最後一個1變為0

假設是2的次方,則n&(n - 1)=0

class Solution {
public:
    bool isPowerOfTwo(int n) {
        //if (!n) return false; // 有可能是負數。故不行
        if (n <= 0) return false;
        return ( n&(n - 1) )== 0;
    }
};



leetcode-231-Power of Two