博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
987. Binary Number with Alternating Bits
阅读量:4676 次
发布时间:2019-06-09

本文共 1141 字,大约阅读时间需要 3 分钟。

Description

Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.

Example

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.
public class Solution {    /**     * @param n: a postive Integer     * @return: if two adjacent bits will always have different values     */    public boolean hasAlternatingBits(int n) {        // Write your code here                //通过位运算,判断到最高位(最高为肯定为1)        while(n != 0) {            //取出尾数            int temp = n % 2;            //将n移位,取出尾数            n= n >> 1;                        //取出移位之后的尾数            int test = n % 2;            //  用过异或判断是否不同(不同便是1)            if((temp ^ test) != 1) {                return false;            }        }                        return true;    }}

转载于:https://www.cnblogs.com/browselife/p/10645609.html

你可能感兴趣的文章
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
查看>>
用原生javascript做的一个打地鼠的小游戏
查看>>
小米手机 - Charles无法安装证书 因为无法读取证书
查看>>
android 动态壁纸开发
查看>>
你误解了Windows的文件后缀名吗?
查看>>
谷歌浏览器插件
查看>>
gcc malloc/free的质疑
查看>>
Servlet注解
查看>>
今后几个月的IT读书计划
查看>>
蓝桥杯 传球游戏 动态规划
查看>>
apk反编译、smali修改、回编译笔记
查看>>
.Net程序员学习Linux最简单的方法(转载)
查看>>
Django DEBUG=False
查看>>
把实体 转为json 数据格式---jackson 的详细用法.
查看>>
数据库管理软件的由来
查看>>
Servlet容器如何处理请求资源路径
查看>>
Linux find 用法示例
查看>>
强悍高效率 92% Nixie Tube 升压电路 12V升150-250V(转)
查看>>
Happy Programming Contest
查看>>
四、K8S
查看>>