zoukankan      html  css  js  c++  java
  • 华为机试-求最大连续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. }  
  • 相关阅读:
    需求规格说明书
    需求规格说明书模板0.2版本
    需求规格说明书模板0.1版本
    万事开头难,团队一起盘!!
    工程开始了!(2019-03-04)
    SpringBoot RESTful API返回统一数据格式还不懂?
    Springboot读取配置文件中的属性
    java本地缓存的使用
    解决github访问不了和慢的问题2021-06-27
    Oracle DDL
  • 原文地址:https://www.cnblogs.com/wwjldm/p/7158685.html
Copyright © 2011-2022 走看看