LeetCode题解之Binary Number with Alternating Bits

1、题目描述

2、问题分析

将数值转换为二进制,然后将前面的 0 去掉,再遍历一边二进制字符串,对每个字符和其后部的字符进行比较。

3、代码

 1  bool hasAlternatingBits(int n) {
 2         if( n <= 1)
 3             return true;
 4         bitset<32> b(n) ;
 5         string s = b.to_string() ;
 6         string::iterator it = s.begin() ;
 7         while( it != s.end() ){
 8             if( *it != '0' )break;
 9             ++it;
10         }
11         
12         s.assign(it,s.end() );
13         it = s.begin() ;
14         while( it != s.end()-1 ){
15             if( *it == *(it + 1) ) return false;
16             ++it;
17         }
18         return true;
19     }

猜你喜欢

转载自www.cnblogs.com/wangxiaoyong/p/9303368.html