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 .
풀이
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String result = "";
while(true){
if (n > 0) {
int a = n % 2;
n = n / 2;
result += String.valueOf(a);
} else {
break;
}
}
String test = new StringBuffer().append(result).reverse().toString();
int count = 1;
int max = 0;
for (int i = 0; i < test.length() - 1; i++) {
if (test.charAt(i) == '1' && test.charAt(i+1) == '1'){
count ++;
} else {
count = 1;
}
max = Math.max(count, max);
}
System.out.println(max);
}
}
처음 썼던 방법인데 Integer.toBinaryString(); 메소드로 쉽게 이진수로 바꿀 수 있다
'Algorithms > 30 Days of Code' 카테고리의 다른 글
Day 13: Abstract Classes (0) | 2018.02.23 |
---|---|
Day 11: 2D Arrays (0) | 2018.02.20 |
Day 9: Recursion (0) | 2018.02.19 |
Day 8: Dictionaries and Maps (0) | 2018.02.19 |
Day 7: Arrays (0) | 2018.02.19 |