天天看點

LeetCode之Power of Two

1、題目

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

Credits:

Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Subscribe to see which companies asked this question.

2、分析

比如我們發現1、2、4、8、16轉化成二進制為

1、10、100、1000、10000、

我們發現第一位是1後面都是0

思路1、

我們先把這個數字和1進行&操作得到一個數temp,然後原數右移動,然後把右移的數字再和1進行&操作,然後和temp相加,如果都是1000,temp之元數不是1之前都是0,最後一次右移動,就成了1,temp == 1,就可以了傳回是

思路2、

我們原素減去-1和元素&操作,如果結果為0就說明是。

3、代碼實作

C++代碼實作1

class Solution {

public:

   bool isPowerOfTwo(int n) {

       int temp = 0;

       while (n > 0) {

           temp += (n & 1);

           n >>= 1;

       }

       return temp == 1;

   }

};

C++代碼實作2

        return (n > 0) && !(n & (n - 1));

java代碼實作2

public class Solution {

   public boolean isPowerOfTwo(int n) {

       return (n > 0) && ((n & (n - 1)) == 0 ? true : false);

}