Title Description:
The maximum number of consecutive digits in a binary number corresponding to a byte number, for example, 3 for binary 00000011, and 1 for 2 consecutive 1
Input:
A byte-type number
Output:
The maximum number of consecutive digits in the corresponding binary number 1
Ideas:
The shift operation can be used to determine the value of each bit 0, 1, and then the results can be obtained by statistics.
ImportJava.util.Scanner;//the range of byte is -128~127 Public classMaxcontinueone { Public Static voidMain (string[] args) {//reads an integer of type byteScanner cin =NewScanner (system.in); bytenum =Cin.nextbyte (); Cin.close (); intmax = 0;//record the maximum number of consecutive bit bits intCount = 0;//temporarily record the current number of consecutive bit bits inttemp = 1 ; BooleanLastflag =false;//record last bit 0 (false) or 1//The byte type is 8 bits, so you can do it 8 times. for(inti = 0; I < 8; i++){ //temp & num Not 0 indicates the current bit is 1 if(Temp & num)! = 0){ if(Lastflag) {count++ ; }Else{Count= 1 ; Lastflag=true ; } //Count The maximum number of consecutive bit digits as Maxmax = max > count?Max:count; }Else{Lastflag=false ; } //Move the temp to the left one bit and go to the next bit to prepare for the comparisontemp = Temp << 1 ; } System.out.println (max); }}
Huawei OJ Platform--maximum consecutive bit count