• 华为机试-求最大连续bit数


    题目描述
    功能: 求一个byte数字对应的二进制数字中1的最大连续数,例如3的二进制为00000011,最大连续2个1

    输入: 一个byte型的数字

    输出: 无

    返回: 对应的二进制数字中1的最大连续数
    输入描述:
    输入一个byte数字
    输出描述:
    输出转成二进制之后连续1的个数
    示例1
    输入

    3
    输出

    2

    程序实现

    1. import java.util.Scanner;  
    2.   
    3. /** 
    4.  * 功能: 求一个byte数字对应的二进制数字中1的最大连续数,例如3的二进制为00000011,最大连续2个1 
    5.  *  
    6.  * 输入: 一个byte型的数字 
    7.  *  
    8.  * 输出: 无 
    9.  *  
    10.  * 返回: 对应的二进制数字中1的最大连续数 输入描述: 输入一个byte数字 输出描述: 输出转成二进制之后连续1的个数 示例1 输入 
    11.  *  
    12.  * 3 输出 
    13.  *  
    14.  * 2 
    15.  *  
    16.  */  
    17. public class Main {  
    18.     public static void main(String[] args) {  
    19.         @SuppressWarnings("resource")  
    20.         Scanner scanner = new Scanner(System.in);  
    21.         while (scanner.hasNext()) {  
    22.             int num = scanner.nextInt();  
    23.             int result = checkMax(num);  
    24.             System.out.println(result);  
    25.         }  
    26.   
    27.     }  
    28.   
    29.     private static int checkMax(int num) {  
    30.         int count = 0;  
    31.         boolean start = false;  
    32.         int current = 0;  
    33.         int flag = 1;  
    34.         while (flag != 0) {  
    35.   
    36.             if ((num & flag) != 0) {  
    37.                 if (!start) {  
    38.                     start = true;  
    39.                     current = 1;  
    40.                 } else {  
    41.                     current++;  
    42.                 }  
    43.   
    44.             } else {  
    45.                 if (count < current) {  
    46.                     count = current;  
    47.                 }  
    48.                 current = 0;  
    49.                 start = false;  
    50.             }  
    51.             flag = (flag << 1);  
    52.         }  
    53.         return count;  
    54.     }  
    55.   
    56. }  
  • 相关阅读:
    OpenFileMapping
    findwindow
    CopyMemory
    SetWindowsHookEx
    fillchar
    什么是ashx文件
    WPF中的控件
    WPF X名称空间里都有什么
    XAML语法学习之...
    Repeater控件使用总结
  • 原文地址:https://www.cnblogs.com/wwjldm/p/7158685.html
Copyright © 2020-2023  润新知