码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-05-19 07:54:52      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:

【华为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;
    }
}

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

标签:

原文地址:http://blog.csdn.net/derrantcm/article/details/51450640

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!