Problem
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.
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 .
How I solved the problem
#10진수를 계속 2로 나누어서 나온 나머지를 2진수로 바꿀 수 있음.
#연속된(consecutive) 1의 최대 개수를 찾는 것 이라서 compCount와 count 두개를 가지고 비교해야함!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; public class Solution { private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) { int n = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); int count = 0; int compCount = 0; while (n > 0) { if (n % 2 == 1) { compCount ++; if (count < compCount) { count = compCount; } } else if (n % 2 == 0) { compCount = 0; } n = n / 2; } if (count == 0) { count = compCount; } System.out.println(count); scanner.close(); } } | cs |
[출처 : https://www.hackerrank.com ]
'1 Day 1 Algorithms' 카테고리의 다른 글
[2018.12.27] Abstract Classes (0) | 2018.12.27 |
---|---|
[2018.12.26] Inheritance (0) | 2018.12.26 |
[2018.12.20] Recursion 3 (0) | 2018.12.21 |
[2018.12.19] Mini-Max Sum (0) | 2018.12.19 |
[2018.12.19] Dictionaries and Maps (0) | 2018.12.19 |
댓글