Given an integer, write a function to determine if it is a power of two.
<Solution>
判斷 int 是否為 2 的次方數,想法如下
- 如果是 2 的次方數,那麼此 int 的 binary 表示裡面,只會有一個 bit 為 1。運用 Number of 1 Bits 的概念即可
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
bool isPowerOfTwo(int n) { | |
int cnt = 0; | |
while(n > 0) { | |
cnt += (n & 1); | |
n >>= 1; | |
} | |
return (cnt == 1); | |
} | |
}; |
- 如果是 2 的次方數,MSB 會是 1,其餘會是 0。假設 n 是 2 的次方數,那麼 n & (n-1) 一定會是 0
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
bool isPowerOfTwo(int n) { | |
return n > 0 && !(n & (n-1)); | |
} | |
}; |
沒有留言:
張貼留言