[codility] Lession1 - Iterations - BinaryGap

Posted Ethan Plan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[codility] Lession1 - Iterations - BinaryGap相关的知识,希望对你有一定的参考价值。

Task1:

A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.

For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps.

Write a function:

    function solution($N);

that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn\'t contain a binary gap.

For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5.

Assume that:

    N is an integer within the range [1..2,147,483,647].

Complexity:

    expected worst-case time complexity is O(log(N));
    expected worst-case space complexity is O(1).

My Solution in php:

// you can write to stdout for debugging purposes, e.g.
// print "this is a debug message\\n";

function solution($N) {
    $binary = decbin($N);
    $ret = 0;
    
    // echo $binary . "\\n";
    
    // 1111 situation
    // 0100 situation
    if ( ( false === strpos($binary, \'0\') )
        || ( stripos($binary, \'1\') == strrpos($binary, \'1\') )
    ) {
        // 默认 $ret = 0 的情况   
    } else {
    
        $cnt = strlen($binary);       
        $idx = null;
        
        for ($i = 0; $i < $cnt; $i++) {        
            if ($binary[$i] == 1) {             
                if ( is_null($idx) ) {
                    // 第一个idx记下来
                    $idx = $i;    
                } else {
                    // 第二个开始计算距离
                    $tmp = $i - $idx - 1;         
                    $ret = ($tmp > $ret) ? $tmp : $ret;
                    // 把当前$i记为上一次1出现时的idx
                    $idx = $i;
                }
            }          
        }    
    }
    
    return $ret;
}

 

Lession1: https://codility.com/programmers/lessons/1-iterations/

Results: https://codility.com/demo/results/trainingU2ACFM-7PE/

Link: http://www.cnblogs.com/farwish/p/6664049.html

以上是关于[codility] Lession1 - Iterations - BinaryGap的主要内容,如果未能解决你的问题,请参考以下文章

Codility 任务 TapEquilibrium 正确性仅为 33%

Solution to Triangle by Codility

CountNonDivisible - Codility 训练任务

Solution of NumberOfDiscIntersections by Codility

需要解决的 Codility 测试

the solution of CountNonDivisible by Codility