remagine
알고리즘 풀기 (12) : A binary gap 본문
A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.
For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps.
Write a function:
class Solution { public int solution(int N); }
that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap.
For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5.
Assume that:
- N is an integer within the range [1..2,147,483,647].
Complexity:
- expected worst-case time complexity is O(log(N));
- expected worst-case space complexity is O(1).
정수를 바이트로 바꾸었을 때 나오는 1과 0의 집합에서
연속된 0의 최대 길이를 구하는 문제이다.
중요한 점은 1과 1사이의 0의 최대길이이다
100100000 에서 최대길이는 2이다. 뒤에 0 6자리는 1 사이가 아니기 때문에 제외된다.
내 해결책
import java.util.ArrayList;
import java.util.Collections; public class Solution { public int solution(int N) { int result = 0; // write your code in Java SE 8 Solution sol = new Solution(); int[] array = sol.intToArray(N); ArrayList<Integer> list = new ArrayList<Integer>(); int order =0; for(int a : array){ order++; if(a==0){ result++; } else if(a==1){ list.add(result); result=0; } } Collections.sort(list); if(list.size() > 0) { result = list.get(list.size()-1); } else { result = 0; } return result; } public int[] intToArray(Integer N) { String items = Integer.toBinaryString(N); int[] results = new int[items.length()]; for (int i = 0; i < items.length(); i++) { try { results[i] = Integer.parseInt(items.substring(i,i+1)); } catch (NumberFormatException nfe) { //NOTE: write something here if you need to recover from formatting errors }; } return results; } }'알고리즘' 카테고리의 다른 글
알고리즘 풀기 (10) 문자열 반복 (약간 쉬움) (0) | 2017.08.11 |
---|---|
알고리즘 풀기 (9) 벌집 (보통) (0) | 2017.07.20 |
알고리즘 풀기 (8) 분수찾기 (보통) (0) | 2017.06.29 |
알고리즘 풀기 (7) 알파벳 찾기 (쉬움) (0) | 2017.06.29 |
알고리즘 풀기 (6) OX퀴즈 (쉬움) (0) | 2017.06.27 |