D47 868. Binary Gap

Topic link

868. Binary Gap

Subject analysis

Given a number, calculate the maximum distance between two 1s in its binary representation.

Train of thought

Of course, it’s binary first. Let’s iterate again.

Returns 0 when there is only one 1. Because you can’t compare distances with just one 1.

So let’s go through each of them. I’m going to give each person a distance plus 1.

When 1 occurs, determine whether the current distance is greater than the maximum recorded value. If it is, it covers. Let’s set the distance to zero.

If there is only one 1, return 0. Otherwise return the maximum distance recorded.

The final code


      
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; }}Copy the code

If you find this article useful, you are welcome to subsidize it with love.