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;
}
}