码迷,mamicode.com
首页 > 其他好文 > 详细

[codility] Lession1 - Iterations - BinaryGap

时间:2017-04-04 01:02:35      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:sso   dem   计算   color   tps   cut   exit   cas   amp   

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

标签:sso   dem   计算   color   tps   cut   exit   cas   amp   

原文地址:http://www.cnblogs.com/farwish/p/6664049.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!