zoukankan      html  css  js  c++  java
  • Iterations --codility

    lesson 1:Iterations

    1. BinaryGap-----[100%]

    Find longest sequence of zeros in binary representation of an integer.

    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.

    解题思路:

    • 将整型数据转为二进制,然后利用python的split函数按‘1’分割,再用max函数找到最大的切片即可
    • 注意二进制为全1,或者第一位为1,后面全为0的数,e.g. 1, 100, 11111, 用log次的循环判定下即可
    • 满足于O(log(N))的时间复杂度
    from math import log
    def solution(N):
        # write your code in Python 2.7
        
        #if N == 1:   #can belong to the next for i = 0
        #    return 0
        for i in xrange(int(log(N,2))+1):
            
            tmp = 2**i
            #print tmp
            if tmp == N+1 or tmp == N:
                return 0 
                
        strb = bin(N).split("1")
        #print strb[1:-1]  
    	#last one can't included. e.g.1001000->2, so [1:-1]
        if strb[1:-1] is None:
            #print "test"
            return 0
        return max([len(l) for l in strb[1:-1]])
    
  • 相关阅读:
    hive基本操作与应用
    理解MapReduce计算构架
    熟悉HBase基本操作
    熟悉常用的HDFS操作
    爬虫大作业
    数据结构化与保存
    使用正则表达式,取得点击次数,函数抽离
    爬取校园新闻首页的新闻
    网络爬虫基础练习
    Hadoop综合大作业
  • 原文地址:https://www.cnblogs.com/Qwells/p/5831814.html
Copyright © 2011-2022 走看看