-
BinaryGap알고리즘/Codility 2020. 9. 13. 21:13
문제) 정수 N에서 binaryGap의 최댓값을 찾아라.
binaryGap이란 1로 둘러쌓인 0의 개수로, 예) N이 529일때, 2진수로는 1000010001 이때, binaryGap의 최댓값은 4.
binaryGap이 없으면 return -1;
나의 해답
import java.util.*; class Solution { public int solution(int N) { int answer = 0; if(N == 1 || N == 0){ return answer; } int mok = 0; List<Integer> list = new ArrayList<Integer>(); while (mok != 1) { mok = (N / 2); list.add((N % 2)); if (mok == 1) { list.add(mok); } N = mok; } boolean isCheck = false; int count= 0; for(int i=list.size()-1; i>=0; i--){ // System.out.print(list.get(i)); if(list.get(i) == 1){ isCheck = !isCheck; if(isCheck==false){ answer = Math.max(answer, count); count = 0; isCheck = true; } continue; }else{ if(isCheck){ count++; } } } return answer; } }
https://app.codility.com/demo/results/trainingDZ8W4Q-Z7Y/
'알고리즘 > Codility' 카테고리의 다른 글
MissingInteger (0) 2020.09.13 CyclicRotation (0) 2020.09.13