Codility BinaryGap
바이너리 갭 문제 풀이.
// you can also use imports, for example:// import java.util.*;// you can write to stdout for debugging purposes, e.g.// System.out.println("this is a debug message");class Solution {final int INIT_ONE_INDEX = -1;public int solution(int N) {if(N == 1 ) return 0;// write your code in Java SE 8int result = 0;//2로 나누어 몫이 있을때마다//1. 바이너리갭 게산 : curernt index - lastoneindex - 1/// 1.1. 바이너리갭이 지금까지 갭보다 크면 갱신//2. lastoneindex 갱신int lastOneIndex = INIT_ONE_INDEX;int maxGap = 0;int currentIndex = 0;for(int i = 0; N > 0; ++i){if(hasQuotient(N)){//뒷자리 연속된 0은 1사이의 갭이 아니므로 이렇게 털기if(!isFirstOne(lastOneIndex) ) {int curGap = i - lastOneIndex - 1;if(curGap > maxGap) maxGap = curGap;}lastOneIndex = i;}N = N / 2;}result = maxGap;return result;}private boolean hasQuotient(int N){return (N % 2) == 1;}private boolean isFirstOne(int N){return INIT_ONE_INDEX == N;}}