Problem:
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
Example 1:
1 2 3 4 |
Input: 5 Output: True Explanation: The binary representation of 5 is: 101 |
Example 2:
1 2 3 4 |
Input: 7 Output: False Explanation: The binary representation of 7 is: 111. |
Example 3:
1 2 3 4 |
Input: 11 Output: False Explanation: The binary representation of 11 is: 1011. |
Example 4:
1 2 3 4 |
Input: 10 Output: True Explanation: The binary representation of 10 is: 1010. |
Idea:
Bit operation
Solution
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Author: Huahua // Runtime: 6 ms class Solution { public: bool hasAlternatingBits(int n) { int r = n & 1; while ((n >>= 1) > 0) { int t = n & 1; if (t == r) return false; r = t; } return true; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment