c语言sscanf函数的用法是什么
239
2022-09-15
[leetcode] 693. Binary Number with Alternating Bits
Description
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
Example 1:
Input: 5Output: TrueExplanation:The binary representation of 5 is: 101
Example 2:
Input: 7Output: FalseExplanation:The binary representation of 7 is: 111.
Example 3:
Input: 11Output: FalseExplanation:The binary representation of 11 is: 1011.
Example 4:
Input: 10Output: TrueExplanation:The binary representation of 10 is: 1010.
分析
题目的意思是: 给一个树,分解成二进制,相邻两个二进制数要不一样,是一个easy题目,解法很直接,我这里给出一个比较好的解法。
我想的方式和这个类似,但是没有想到右移一位来解决这个问题。
代码
class Solution {public: bool hasAlternatingBits(int n) { int d=n&1; while((n&1)==d){ d^=1; n>>=1; } return n==0; }};
参考文献
[LeetCode] Binary Number with Alternating Bits 有交替位的二进制数
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~