Saturday, July 09, 2016

Consecutive 1s in Integer

Task
Given a base- integer, , convert it to binary (base-). Then find and print the base- integer denoting the maximum number of consecutive 's in 's binary representation.
Input Format
A single integer, .
Constraints

Output Format
Print a single base- integer denoting the maximum number of consecutive 's in the binary representation of .
Sample Input 1
5
Sample Output 1
1
Sample Input 2
13
Sample Output 2
2
Explanation
Sample Case 1:
The binary representation of is , so the maximum number of consecutive 's is .
Sample Case 2:
The binary representation of is , so the maximum number of consecutive 's is .

Analysis:
use and(&) operation with a mask of 1 to tell if right most bit is 1, if it is 1, then a counter will be increased one. and max will try to track the current max length of 1s. otherwise, reset counter.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int max = 0, cnt=0;
        in.close();
        for(int i=0;i<32;i++){
            if((n&1)==1){
                cnt++;//counter 1s
                max = Math.max(max,cnt);//update max consecutive 1s numbers
            }else
                {
                cnt=0;//reset counter
            }
            n=n>>>1;//unsigned shift, so padding it with 0
        }
        System.out.println(max);
    }
}

No comments: