java题目 HJ86 求最大连续bit数

描述

求一个int类型数字对应的二进制数字中1的最大连续数,例如3的二进制为00000011,最大连续2个1

本题含有多组样例输入。
数据范围:数据组数:1\le t\le 5\1t5 ,1\le n\le 500000\1n500000 
进阶:时间复杂度:O(logn)\O(logn) ,空间复杂度:O(1)\O(1) 

输入描述:

输入一个int类型数字

输出描述:

输出转成二进制之后连续1的个数

示例1

输入:
3
5
200
输出:
2
1
2
说明:
3的二进制表示是11,最多有2个连续的1。
5的二进制表示是101,最多只有1个连续的1。   

 

 1 import java.io.*;
 2 import java.util.*;
 3 
 4 public class Main{
 5     public static void main(String[] args) throws IOException {
 6         Scanner sc = new Scanner(System.in);
 7         while(sc.hasNext()) {
 8             int number = sc.nextInt();
 9             String ch = Integer.toBinaryString(number);
10             int count = 0;
11             int max = 0;
12             for (int i = 0 ; i < ch.length(); i++) {
13                 if(ch.charAt(i) == '1'){
14                     count++;
15                     max = Math.max(max, count);
16                 }else{
17                     count =0;
18                 }
19             }
20             System.out.println(max);
21         }
22     }
23 }

 

posted @ 2022-03-06 16:15  海漠  阅读(101)  评论(0)    收藏  举报