Objective
Today, we're working with binary numbers. Check out the Tutorial tab for learning materials and an instructional video!

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. When working with different bases, it is common to show the base as a subscript.

Example

The binary representation of  is . In base , there are  and  consecutive ones in two groups. Print the maximum, .

Input Format

A single integer, .

Constraints

  • 1 <= n <= 10(6)

Output Format

Print a single base- integer that denotes 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 .

 


  1. 주어진 정수를 2진수 변환하여 1이 연속해있는것이 몇번인지 출력해줘야함.
  2. 받은 정수 2로 나누어 나머지값을 2진법으로 저장
  3. 거꾸로 저장되어있으니 reverse
  4. 나온 문자열로 반복문 돌리고 인접한 1이 있으면 cnt증가 
  5. cnt가 answer 보다 커지면 answer의 값을 cnt로 대체 

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;



public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

        int n = Integer.parseInt(bufferedReader.readLine().trim());
        int answer = 1;
        
        String binary = "";
        
        while(n > 0) {
            if(n % 2 == 0) {
                binary += "0"; 
            } else {
                binary += "1";
            }
            n = n/2;
        }
        
        StringBuffer sb = new StringBuffer(binary);
        binary = sb.reverse().toString();
        int cnt = 1;
        for(int i=1; i<binary.length(); i++) {
            
            if(binary.charAt(i) == binary.charAt(i-1)) {
                cnt++;
                if(cnt > answer) {
                    answer = cnt;
                }
            } else {
                cnt = 1;
            }
        }

        System.out.print(answer);
        
        bufferedReader.close();
    }
}

'알고리즘 > Hackerrank' 카테고리의 다른 글

[Hackerrank] Ingeritance  (0) 2021.10.10
[Hackerrank] 2D Arrays  (0) 2021.10.10
[Hackerrank] Recursion 3  (0) 2021.10.10
[Hackerrank] Dictionaries and Maps  (0) 2021.10.05
[Hackerrank] Arrays  (0) 2021.10.02