Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
Example 1:
Input: 5 Output: True Explanation: The binary representation of 5 is: 101
Example 2:
Input: 7 Output: False Explanation: The binary representation of 7 is: 111.
Example 3:
Input: 11 Output: False Explanation: The binary representation of 11 is: 1011.
Example 4:
Input: 10 Output: True Explanation: The binary representation of 10 is: 1010. 判断一个数的二进制中,01是否是交替出现的 C++(3ms):
1 class Solution { 2 public: 3 bool hasAlternatingBits(int n) { 4 int t1 , t2 ; 5 t1 = n%2 ; 6 n/=2 ; 7 while(n){ 8 t2 = n%2 ; 9 n/=2 ; 10 if (t2 == t1) 11 return false ; 12 t1 = t2 ; 13 } 14 return true ; 15 } 16 };
C++(3ms):
1 class Solution { 2 public: 3 bool hasAlternatingBits(int n) { 4 int d = n&1 ; 5 while((n&1) == d){ 6 d = 1-d ; 7 n >>= 1 ; 8 } 9 return n == 0 ; 10 } 11 };
java(14ms):
1 class Solution { 2 public boolean hasAlternatingBits(int n) { 3 int d = n&1 ; 4 while((n&1) == d){ 5 d = 1-d ; 6 n >>= 1 ; 7 } 8 return n == 0 ; 9 } 10 }
时间: 2024-11-06 02:03:48