BinaryGap

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:
int solution(int 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).

下面给出我的解决方案,如果有其他的答案,欢迎大家一起讨论:


BinaryGap.png
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,164评论 0 10
  • 一、上次上了GsonFormat的当,这次上了ButterKnifer(快速绑定资源Id)的当~ 一般情况,使用B...
    了不起的潘阅读 825评论 0 1
  • 看鹏皓聚精会神读书的样子,读一本好书,开阔孩子视野的启蒙书——睡前故事。兴趣是阅读的动力,好书是孩子成长最好的营养...
    鹏皓妈咪阅读 786评论 0 0
  • 前些日子和土豆聊天。 土豆问我说《爱情保卫战》那档子节目里面的故事是不是真的。 我想了一下和他说要是以后有一天你和...
    方不见阅读 8,256评论 26 56