Leetcode PHP题解--D58 693. Binary Number with Alternating Bits


D58 693. Binary Number with Alternating Bits

题目链接

693. Binary Number with Alternating Bits

题目分析

给定一个数字,返回其二进制形式中,0和1是否交替出现。

思路

判断给定的数字是否为奇数。
若为奇数,那么最低位(即最右)会为1,那么会重复出现01串。
若为偶数,最低位为0,那么只能重复出现10串。

根据以上规则创建长度为给定数字二进制长度一半的01串,并转换为十进制。

判断转换后的数字是否等于给定的字符。

最终代码

<?php
class Solution {

    /**
     * @param Integer $n
     * @return Boolean
     */
    function hasAlternatingBits($n) {
        $match = str_repeat($n%2==0?'10':'01',ceil(count(str_split(decbin($n)))/2));
        return bindec($match) == $n;
    }
}

若觉得本文章对你有用,欢迎用爱发电资助。


点赞 取消点赞 收藏 取消收藏

<< 上一篇: Leetcode PHP题解--D57 762. Prime Number of Set Bits in Binary Representation

>> 下一篇: Leetcode PHP题解--D59 226. Invert Binary Tree