HJ86 求最大连续 bit 数

HJ86 求最大连续 bit 数

描述

求一个 int 类型数字对应的二进制数字中 1 的最大连续数,例如 3 的二进制为 00000011,最大连续 2 个 1
数据范围:数据组数:1≤t≤5 1≤t≤5 ,1≤n≤500000 1≤n≤500000
进阶:时间复杂度:O(logn) O(logn) ,空间复杂度:O(1) O(1)

输入描述:

输入一个 int 类型数字

输出描述:

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

示例 1

输入:
200
输出:
2

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

题解

位运算
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) {
            // 输入一个int类型数字
            int a = in.nextInt();
            // 输出转成二进制之后连续1的个数
            int res = getRes(a);
            System.out.println(res);
        }
    }
    public static int getRes(int a) {
        // 输出转成二进制之后连续1的个数
        int res = 0;
        // 最大连续
        int max = 0;
        while (a != 0) {
            if (a % 2 == 1) {
                res++;
            } else {
                res = 0;
            }
            max = Math.max(res, max);
            a = a >> 1;
        }
        return max;
    }
}
进制转换
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new  Scanner(System.in);
        while (sc.hasNext()) {
            int a = sc.nextInt();
            int res = getRes(a);
            System.out.println(res);
        }
    }
    public static int getRes(int a) {
        int res = 0;
        int max = 0;
        String s = Integer.toBinaryString(a);
        for (char c : s.toCharArray()) {
            if (c == '1') {
                res++;
            } else {
                res = 0;
            }
            max = Math.max(max, res);
        }
        return max;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值