求最大连续bit数

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

数据范围:数据组数:1≤t≤51≤n≤500000

进阶:时间复杂度: O(logn) ,空间复杂度: O(1)

输入描述:

输入一个int类型数字

输出描述:

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

示例1

输入

200

输出

2

说明

200的二进制表示是11001000,最多有2个连续的1。

Java 编程

package cn.net.javapub.demo2.demo;

/**
 * @author: shiyuwang
 */

import java.util.*;
import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str;
        while ((str = br.readLine()) != null) {
            int n = Integer.parseInt(str);
            int res = 0;
            int zere = 0;
            //一直取最后一位,
            while (n != 0) {
                if (n % 2 == 1) {
                    zere++;
                    if (zere > res) {
                        res = zere;
                    }
                } else {
                    zere = 0;
                }
                n /= 2;
            }
            System.out.println(res);
        }
    }
}

展示效果:

华为OD机试 - 最长回文子串 (Java 2024 E卷 100分)_华为od