求整数最大的连续0的个数 

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:

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).
package com.codility;
public class Test01 {
public int solution(int N) {
if(N<=0){
return 0;
}
String str = Integer.toBinaryString(N);
int size = str.length();
int count=0;
int max = 0;
for(int i=0;i<size;i++){
String str01 = str.substring(i, i+1);
if(str01.equals("1")){
if(count>0){
max = Math.max(count, max);
}
count = 0;
}
if(str01.equals("0")){
count ++;
}
}
return max;
}
public static void main(String[] args) {
String str = Integer.toBinaryString(20);
System.out.println(str);
// System.out.println(str.substring(0, 1));
Test01 t01 = new Test01();
System.out.println(t01.solution(5));
System.out.println(t01.solution(20));
System.out.println(t01.solution(529));
}
}

最新文章

  1. Atitit sql执行计划
  2. KEIL MDK STM32如何建立工程
  3. IntelliJ IDEA使用(2)——IDEA配置Tomcat
  4. SGU 180 Inversions(离散化 + 线段树求逆序对)
  5. WITH AS短语,也叫做子查询部分(subquery factoring)
  6. Google十大惊人产品
  7. 实现图片的2次缩放后再进行candy边缘检测
  8. Assembly(c#中简单说明[转]
  9. CentOS下系统时间同步和时区的修改和设置(用的这个)
  10. Ubuntu12.04password正确 入口的桌面(测试的恢复正常)
  11. javascript 深入浅出 (未完成4-17)
  12. Jenkins + Gradle + pgyer + Android自动发布
  13. 配置多个git账号的ssh密钥
  14. 18-09-15 潘一刘老师 讲课replace 控件输入函数检测的包
  15. java中super关键字的作用
  16. $Matrix-Tree$定理-理论
  17. SQL Server 一句Sql把表结构全部查询出来
  18. [C++] set与multiset的常用函数
  19. JavaScript权威指南第02章 词法结构
  20. python中for...if...构建List

热门文章

  1. Python(1)-第一天
  2. mysql的简单优化【简单易学】
  3. switch-case用法
  4. web安全测试--XSS(跨站脚本)与CSRF
  5. ProcessBar 与SeekBar进度条
  6. dede手机访问网站跳转到手机端模板
  7. UVM基础之---------Reporting Classes
  8. 动态代理在WEB与JDBC开发中的应用
  9. RabbitMQ调用
  10. MySQL学习笔记(十二)__连接查询(一)