codility Lesson 풀어보기

Coding Test 준비/codility 2022. 6. 19. 14:30

이미 굳어버린 머리에 산소호흡 시켜보고자 강의 수강외에 코딩 테스트도 추가로 풀기로 함.

첫 시작은 codility Lesson 부터 시작 (06.19)

 

Codility Lesson 1. binary Gap

// 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 {
    public int solution(int N) {
        // write your code in Java SE 8
        String binaryCode;
		int maxGap;
		boolean checkValue;

		//get binary code
		binaryCode = getBinaryCode(N);

		//validate binaryCode
		checkValue = validateBinaryCode(binaryCode);

		//validation failed string return without calculation
		if(!checkValue) return 0;

		//get max gap value
		maxGap = getMaxGap(binaryCode);

		return maxGap;
	}

	private static int getMaxGap(String binaryCode) {
		int gapNum=0, maxGap=0;
		for(int i=0; i<binaryCode.length(); i++) {
			if (binaryCode.charAt(i) == '0') {
				gapNum++;
			} else {
				if (gapNum > maxGap) {
					//update max Gap Num
					maxGap = gapNum;
				}
				//init gapNum count
				gapNum = 0;
			}
		}
		return maxGap;
	}

	private static boolean validateBinaryCode(String binaryCode) {
		//0, 1, 00, 01, 10, 10 is no gap
		if(binaryCode.length()<2) return false;

		//check string has only '1' value
		if (binaryCode.indexOf('0')<0) return false;

		//check string has only one '1' value
		if(binaryCode.indexOf('1') == binaryCode.lastIndexOf('1')) return false;

		//add additional validation code

		return true;
	}

	private static String getBinaryCode(int n) {
		return Integer.toBinaryString(n);
	}
}

 

 

결과 : 

 

'Coding Test 준비 > codility' 카테고리의 다른 글

codility Lesson 풀어보기 6  (0) 2022.08.20
codility Lesson 풀어보기 5  (0) 2022.08.15
codility Lesson 풀어보기 4  (0) 2022.08.06
codility Lesson 풀어보기 3  (0) 2022.06.29
codility Lesson 풀어보기 2  (0) 2022.06.26