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

栏目: PHP · 发布时间: 6年前

内容简介:给定一个数字,返回其二进制形式中,0和1是否交替出现。判断给定的数字是否为奇数。

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;
    }
}

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


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Algorithms + Data Structures = Programs

Algorithms + Data Structures = Programs

Niklaus Wirth / Prentice Hall / 1975-11-11 / GBP 84.95

It might seem completely dated with all its examples written in the now outmoded Pascal programming language (well, unless you are one of those Delphi zealot trying to resist to the Java/.NET dominanc......一起来看看 《Algorithms + Data Structures = Programs》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具