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.

含义:让我们判断一个二进制数的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     }
复制代码

 

posted @   daniel456  阅读(208)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示