문제: 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
영어가 어려워서, 구글번역기를 사용했다.
문제 파악하기
1. 양수(N)를 2진수로 바꿔서 연속된 0의 수가 최대인 값을 계산하자(1과 1사이의 가장 먼 거리 계산하기)
2. 9 = 1001 일 경우 2
529 = 1000010001 일 경우 4
20 = 10100 일 경우 1
32 = 100000 일 경우 0
3. N의 범위는 1 ~ 2147483647
문제 풀기
1. 1의 위치(index) 파악하기
2. 1과 1사이의 거리 구하기 (근데 0의 갯수니깐 거리에서 - 1 해주자)
3. 1의 위치값이 0 또는 1이면 거리가 없으니 0 리턴.
코드구현 (C#)
string binary = Convert.ToString(N, 2); // 2진수로 바꾸기
char[] binaryArray = binary.ToCharArray(); // 배열에 담자. 왜? index 구하고 싶으니깐
List<int> list = new List<int>(); // index 담을 리스트. index가 몇 개 있을지 모르니깐..
for (int i = 0; i < binaryArray.Length; i++)
{
if (binaryArray[i].Equals('1')) // 1에 해당하는 index 찾자
list.Add(i);
}
if (list.Count >= 2) // 밸셈을 하려면 2개 이상의 숫자가 필요
{
int result = 0;
int calc = 0;
for (int i = list.Count - 1; i > 0; i--)
{
calc = list[i] - list[i - 1] - 1;
if (calc > result) // 가장 큰 수를 찾아보자
result = calc;
}
return result;
}
return 0;
100점인거 보고 쉬우니깐!! 이라고 생각하고, 다른 사람들은 어떻게 풀었나 봤더니..
아.. 공부를 더해야겠구나.. 싶다.
어느 순간부터 습관처럼 코딩했는데.. 이제 머리도 좀 쓰고 고민을 더 해봐야 겠다.
'공부하자 > Codility' 카테고리의 다른 글
[Codility] Lesson3. TapeEquilibrium (C#) (0) | 2020.11.17 |
---|---|
[Codility] Lesson3. PermMissingElem (C#) (0) | 2020.11.17 |
[Codility] Lesson3. FrogJmp (C#) (0) | 2020.11.17 |
[Codility] Lesson2. CyclicRotation (C#) (0) | 2020.11.17 |
[Codility] Lesson2. OddOccurrencesInArray (C#) (0) | 2020.11.17 |