Leetcode PHP题解--D47 868. Binary Gap

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

内容简介:给定一个数字,计算其二进制表示中,出现的两个1最大距离。当然是先转换成二进制了。再进行遍历。

D47 868. Binary Gap

题目链接

868. Binary Gap

题目分析

给定一个数字,计算其二进制表示中,出现的两个1最大距离。

思路

当然是先转换成二进制了。再进行遍历。

当只有一个1时,返回0。因为只有一个1是没办法比较距离的。

逐个遍历每位。每位都给距离+1。

当出现1时,判断当前距离是否大于记录的最大值。是则覆盖。再把距离置零。

最后判断当只有一个1时,直接返回0。否则返回所记录的最大距离。

最终代码

<?php
class Solution {
    public $max = 0;
    function binaryGap($N) {
        $bin = decbin($N);
        $chars = str_split($bin);
        $len = 0;
        $max = 0;
        $ones = 0;
        foreach($chars as $key=>$char){
            $len++;
            if($char == '1'){
                $ones++;
                if($len>$max){
                    $max = $len;
                }
                $len = 0;
            }
        }
        return $ones>1?$max:0;
    }
}

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


以上所述就是小编给大家介绍的《Leetcode PHP题解--D47 868. Binary Gap》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

Algorithms to Live By

Algorithms to Live By

Brian Christian、Tom Griffiths / Henry Holt and Co. / 2016-4-19 / USD 30.00

A fascinating exploration of how insights from computer algorithms can be applied to our everyday lives, helping to solve common decision-making problems and illuminate the workings of the human mind ......一起来看看 《Algorithms to Live By》 这本书的介绍吧!

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具