공부-codility

[Lesson] 1. Iterations

아직해떴다 2022. 8. 4. 15:42

소스코드

// 1. make int to binary
String binaryStr = "";
int tempN = N;
while(true){
	if(tempN == 0){
		break;
	}

	int div = tempN % 2;
	binaryStr = div + binaryStr;
	tempN = tempN / 2;
}
// 2. split by 1
String [] arr = binaryStr.split("1");


int arrCount = 0;
// 3. if end of string is 0
if(binaryStr.substring(binaryStr.length()-1).equals("0")){
	arrCount = arr.length-1;
}
// 4. if end of string i 1
else{
	arrCount = arr.length;
}

// 5. find max length
int max = 0;
for(int i = 0 ; i < arrCount ; i++){
	if(max < arr[i].length())
		max = arr[i].length();
}

 

풀이

1. 10진수를 2진수의 문자열로 변환한다.

2. 1번에서 만든 결과를 문자 "1"을 기준으로 분할시킨다. 

3. (예외처리) 1의 자리 값이 0이라면, 2번에서 생성된 배열의 마지막 값은 사용할 수 없다. 

4. (예외처리) 1의 자리 값이 1이라면, 2번에서 생성된 배열의 마지막 값을 사용할 수 있다. 

5. 문자열 배열의 길이값 max를 구한다.