9/2
4 1
2 0
1 0
0 1

529
264 1
132 0
66 0
33 0
16 1
8 0
4 0
2 0
1 0
0 1

32
16 0
8 0
4 0
2 0
1 0
0 1

数据结构:栈

练习题

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. The number 32 has binary representation 100000 and has no binary gaps.

Write a function:

def 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. Given N = 32 the function should return 0, because N has binary representation '100000' and thus no binary gaps.

Write an efficient algorithm for the following assumptions:

  • N is an integer within the range [1..2,147,483,647].
def solution(N):
def conversionOfNumberSystemsFromDecimalism(decimalismNum, base):
stackContainer = []
N = decimalismNum
b = base
start = N
while True:
m = start % b
start = int(start / b)
stackContainer.append(m)
if start == 0:
break
return stackContainer stackContainer = conversionOfNumberSystemsFromDecimalism(N, 2)
if stackContainer.count(1) <= 1:
return 0
else:
l = stackContainer[stackContainer.index(1):]
s = ''.join([str(i) for i in l])
return max([len(i) for i in s.split('1')])

  

随机推荐

  1. Hightchart 技巧

    http://blog.csdn.net/u014796515/article/details/24428131

  2. 初试WebSocket构建聊天程序

    上一篇文章中使用了Ajax long polling实现了一个简单的聊天程序,对于web实时通信,今天就来试用一下基于WebSocket的长连接方式. WebSocket简介 为了增强web通信的功能 ...

  3. cocos2dx 3.0 scrollview 在android下面背景變綠色了

    在windows上面跑的是OK的,  在android下面跑的時候就變成這樣子了:

  4. sharepoint权限操作(记录以备忘)

    using Microsoft.SharePoint; using System; using System.Collections.Generic; using System.Linq; using ...

  5. 使用 urllib 解析 URL 链接

    urllib 库还提供了 parse 模块,它定义了处理 URL 的标准接口,例如实现 URL 各部分的抽取.合并以及链接转换,常用的方法如下: In []: from urllib.parse im ...

  6. [XPath] XPath 与 lxml (三)XPath 坐标轴

    本章我们将沿用上一章的 XML 示例文档. XPath 坐标轴 坐标轴用于定义当对当前节点的节点集合. 坐标轴名称 含义 ancestor 选取当前节点的所有先辈元素及根节点. ancestor-or ...

  7. ip防刷脚本

    #!/bin/sh #防刷脚本 #env ACCESS_PATH=/home/wwwlogs ACCESS_LOG=y.log IPTABLES_TOP_LOG=iptables_top.log DR ...

  8. 操作系统定期定时执行python脚本

    1. Windows 控制面板 --> 管理工具 -->任务计划程序 --> 创建任务 接下来就是设置执行的时机以及脚本路径等 1>>常规 设置任务名称描述,以及是否执行 ...

  9. 探求C#.Net中ArrayList与Array的区别

     ArrayList与Array的区别概述     ArrayList 是数组的复杂版本.ArrayList 类提供在大多数 Collections 类中提供但不在 Array 类中提供的一些功能.例 ...

  10. Contain的使用