您的位置:首页 > 其它

【华为OJ】【084-求最大连续bit数】

2016-05-19 06:43 381 查看

【华为OJ】【算法总篇章】

【华为OJ】【084-求最大连续bit数】

【工程下载】

题目描述

功能: 求一个byte数字对应的二进制数字中1的最大连续数,例如3的二进制为00000011,最大连续2个1
输入: 一个byte型的数字
输出: 无
返回: 对应的二进制数字中1的最大连续数


输入描述

输入一个byte数字


输出描述

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


输入例子

3


输出例子

2


算法实现

import java.util.Scanner;

/**
* Author: 王俊超
* Date: 2016-01-04 09:44
* Declaration: All Rights Reserved !!!
*/
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//        Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt"));
while (scanner.hasNext()) {
int b = scanner.nextInt();
System.out.println(countBit(b));
}

scanner.close();
}

private static int countBit(int b) {
int max = 0;
int cur = 0;
b &= 0xFF;
for (int i = 0, and = 1; i < 8; i++) {
// 如果第i位为1
if ((b & and) != 0) {
cur++;
if (cur > max) {
max = cur;
}
} else {
cur = 0;
}

and <<= 1;
}

return max;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: