693. Binary Number with Alternating Bits

本文介绍了一个用于检查正整数的二进制表示中1和0是否交替出现的方法。通过给出具体的实现代码及四个实例演示,帮助读者理解如何判断一个二进制数的1和0是否按顺序交替。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

含义:让我们判断一个二进制数的1和0是否是交替出现的

 

 1     public boolean hasAlternatingBits(int n) {
 2 //        char[] chs = Integer.toBinaryString(n).toCharArray();
 3 //        if (chs.length<2) return true;
 4 //        char evenChar = chs[0];
 5 //        char oddChar = chs[1];
 6 //        for(int i=2;i<chs.length;i++)
 7 //        {
 8 //            if (i%2 ==0)
 9 //            {
10 //                if (evenChar != chs[i]) return false;
11 //            }else
12 //                if (oddChar != chs[i]) return false;
13 //        }
14 //        return true;
15         int a=n<<1;
16         int b= n^a;
17         char[] chs = Integer.toBinaryString(b).toCharArray();
18         for (int i=0;i<chs.length-1;i++) if (chs[i] != '1') return false;
19         boolean result = n==(n&b);
20         return result;
21     }

 

转载于:https://www.cnblogs.com/wzj4858/p/7732159.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值