본문 바로가기
공부/Algorithms w.Java

Codility Lesson 1 - BinaryGap; Java

by thegreatjy 2023. 6. 30.
728x90

https://app.codility.com/programmers/lessons/1-iterations/binary_gap/

 

BinaryGap coding task - Learn to Code - Codility

Find longest sequence of zeros in binary representation of an integer.

app.codility.com

영어라서 쫄았는데 굉장히 쉬웠다.

35분 걸렸고 100점 

public class Solution {
	public int solution(int N) {
        // Implement your solution here
		//the max number of 0 
		int max = 0;
		//make binary representation of N 
		String bin = Integer.toBinaryString(N);
		//yield longest bg
		int cntZero = 0;
		for(int i=0;i<bin.length();i++) {	//max length of bin is 32
			if(bin.charAt(i)=='1') {
				//renewal max
				max = Math.max(cntZero, max);
				cntZero = 0;
			}else {
				cntZero++;
			}
		}
		
		return max;
    }
}

1. 숫자 N을 이진수 표현의 String으로 만듦 => Integer.toBinaryString(N) 사용

2. 현재 i에 있는 문자가 1 혹은 0이다

2-1. 1인 경우:

최대 0 개수(max)를 여태까지 나온 0 개수(cntZero)와 비교해서 갱신한다.

여태까지 나온 0 개수를 0개로 초기화한다.

2-2. 0인 경우:

여태까지 나온 0 개수를 하나 늘린다.

728x90