[codility] Lession1 - Iterations - BinaryGap

通过llama.cpp与羊驼聊天的网页界面- 详解 Serge 的启动使用

 

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

 

Refer:BinaryGap

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

posted on 2017-04-03 23:46  ercom  阅读(751)  评论(0编辑  收藏  举报