题目描述
功能: 求一个byte数字对应的二进制数字中1的最大连续数, 例如3的二进制为00000011,最大连续2个1
思路:
利用位运算,不断右移并“与”1,如果“与”的结果是1,说明二进制bit为最后一位的数字是1。
注意:
可能有负数的情况。对于负数的处理思路是:统计0的个数,然后用8减。由于byte在java中占用1个字节,就是8位,所以可以用8减。
import java.util.Scanner; public class Main { // java中byte占1个字节,8位 // 处理正数 public static int solution_positive(int n) { int max = 0; int count = 0; while(n > 0) { // 注意此处是0 if((n & 1) == 1) { count++; max = Math.max(max, count); }else { count = 0; } n = n >> 1; } return max; } // 处理负数 统计0的个数,然后用8减 public static int solution_negtive(int n) { int max = 0; int count = 0; while(n < -1) { // 注意此处是-1 if((n & 1) == 0) { count++; max = Math.max(max, count); }else { count = 0; } n = n >> 1; } return 8 - max; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); while(sc.hasNext()) { int n = sc.nextInt(); if(n >= 0) { int result = solution_positive(n); System.out.println(result); }else { int result = solution_negtive(n); System.out.println(result); } } sc.close(); } }