LeetCode之Power of Two
生活随笔
收集整理的這篇文章主要介紹了
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
?
class Solution { public:bool isPowerOfTwo(int n) {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);} }?
?
?
?
?
總結
以上是生活随笔為你收集整理的LeetCode之Power of Two的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode之Happy Numbe
- 下一篇: LeetCode之Two Sum II