前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LWC 53:693. Binary Number with Alternating Bits

LWC 53:693. Binary Number with Alternating Bits

作者头像
用户1147447
发布2018-01-02 10:58:08
5180
发布2018-01-02 10:58:08
举报
文章被收录于专栏:机器学习入门

LWC 53:693. Binary Number with Alternating Bits

传送门:693. Binary Number with Alternating Bits

Problem:

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.

思路: 熟悉JAVA接口的知道,Integer类可以直接把数字转为2进制串。

代码如下:

代码语言:javascript
复制
    public boolean hasAlternatingBits(int n) {
        String binary = Integer.toBinaryString(n);
        char[] cs = binary.toCharArray();
        int bit = cs[0] - '0';
        for (int i = 1; i < cs.length; ++i) {
            if (bit == cs[i] - '0') return false;
            bit = cs[i] - '0';
        }
        return true;
    }

当然,你也可以自己解析每一位,代码如下:

代码语言:javascript
复制
    public boolean hasAlternatingBits(int n) {
        int bit = n >> 0 & 1;
        n >>= 1;
        while (n > 0) {
            if (bit == (n & 1)) return false;
            bit = n & 1;
            n >>= 1;
        }
        return true;
    }

或者合并到一块:

代码语言:javascript
复制
    public boolean hasAlternatingBits(int n) {
        int bit = -1;
        while (n > 0) {
            if (bit == (n & 1)) return false;
            bit = n & 1;
            n >>= 1;
        }
        return true;
    }    
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017-10-08 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • LWC 53:693. Binary Number with Alternating Bits
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档