693. Binary Number with Alternating Bits

Posted __Meng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了693. Binary Number with Alternating Bits相关的知识,希望对你有一定的参考价值。

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 }

 

 

以上是关于693. Binary Number with Alternating Bits的主要内容,如果未能解决你的问题,请参考以下文章

693. Binary Number with Alternating Bits

693. Binary Number with Alternating Bits - LeetCode

LeetCode 693. Binary Number with Alternating Bits 自我反思

leetcode练习:693. Binary Number with Alternating Bits

Leetcode - 693. Binary Number with Alternating Bits

693. 交替位二进制数