Task description

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:

class Solution { public 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).
 
Solution

 
Programming language used: Java
Total time used: 8 minutes
Code: 09:57:26 UTC, java, final, score:  100
// you can also use imports, for example:
// import java.util.*; // you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message"); class Solution {
public int solution(int N) {
// write your code in Java SE 8
int longest=0,temp=0;
int test = N;
boolean power = false;
if(test % 2 == 0){
test = test / 2;
power = true;
}
while(test !=0) {
if(test % 2 ==0) {
if(power) {
test = test / 2;
continue;
}
temp++;
} else {
temp = 0;
power =false;
}
test = test / 2;
if(longest < temp)
longest = temp;
}
return longest;
}
}
 
 

最新文章

  1. WWW读取安卓外部音乐文件
  2. -bash: /bin/rm: Argument list too long
  3. Hibernate4.1之后关于占位符的问题
  4. linux下定时重启tomcat
  5. SQL疑难杂症【4 】大量数据查询的时候避免子查询
  6. [0x01 用Python讲解数据结构与算法] 关于数据结构和算法还有编程
  7. javascript --- 词法分析
  8. js 返回并刷新
  9. 小心指针被delete两次
  10. jQuery插件之-Poshy Tip
  11. PHP 单态设计模式复习
  12. iOS用户行为追踪——无侵入埋点
  13. alpha冲刺总结随笔
  14. [转]恕我直言,在座的各位根本不会写 Java!
  15. python操作haproxy.cfg文件
  16. [Unity算法]弧度和角度
  17. Hdu4687 Boke and Tsukkomi
  18. Sql server 索引详解
  19. 1.1环境的准备(一)之Python解释器的安装
  20. RLP(转发注明出处)

热门文章

  1. 一款有意思的 Qt 飞行仪表控件
  2. Android 平台下Cordova 调用Activity插件开发
  3. vue 百度地图
  4. 简单IO,将一段字符串存入一个记事本
  5. QList介绍(QList比QVector更快,这是由它们在内存中的存储方式决定的。QStringList是在QList的基础上针对字符串提供额外的函数。at()操作比操作符[]更快,因为它不需要深度复制)非常实用
  6. Windows DPI Awareness for WPF
  7. Microsoft IoT Starter Kit
  8. c#调用ffmpeg嵌入srt/ass字幕提示Unable to open xxx.srt......
  9. OpenCV中基于HOG特征的行人检测
  10. Qt程序调试之Q_ASSERT断言(条件为真则跳过,否则直接异常+崩溃)