java笔试之求最大连续bit数

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

package test;

import java.util.Scanner;

/*
 * 求最大连续bit数
 * 功能: 求一个byte数字对应的二进制数字中1的最大连续数,例如3的二进制为00000011,最大连续2个1
 * 输入: 一个byte型的数字
 * 输出: 无
 * 返回: 对应的二进制数字中1的最大连续数
 * */
public class exam12 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            int num = scanner.nextInt();
            System.out.println(seqByte(num));
            System.out.println(seqByte2(num));
        }
        scanner.close();
    }

    public static int seqByte(int n) {
        //方法一
        int count = 0;
        int max = 0;
        while (n > 0) {
            int x = n & 0x1;
            if (x == 1) {
                count++;
                if (count > max) {
                    max = count;
                }
            } else {
                count = 0;
            }
            n = n >> 1;
        }
        return max;
    }

    public static int seqByte2(int n) {
        //方法二
        int k;
        for (k = 0; n != 0; k++) {
            n = n & (n << 1);
        }
        return k;
    }

}

 

posted on 2017-02-17 15:47  贝拉拉  阅读(166)  评论(0编辑  收藏  举报

导航