[Lession1] Iterations - BinaryGap
정수 N이 주어졌을 때, N을 이진수로 변환한다.
이진수의 1과 1사이에 있는 0의 개수를 계산하고, 그 최대값을 구하는 문제
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
Solution
while 문으로 정수 N을 String 형으로 이진수로 변환한다.
for 반복문으로 '0'과 '1'일 경우를 검사한다.
이때, '0'일 경우 count 값을 더해주고, '1'일 경우에는 한가지 더 검사해야한다.
count 값이 0이 아닐 경우를 같이 검사해서 '1'과 '1'사이의 '0'의 개수를 보장하게 한다.
class Solution {
public int solution(int N) {
StringBuilder s = new StringBuilder();
while (N > 0) {
s.append(N % 2);
N /= 2;
}
s.reverse();
int count = 0, max = 0;
for (char c : s.toString().toCharArray()) {
if (c == '1' && count != 0) {
max = Math.max(max, count);
count = 0;
} else if (c == '0') {
count++;
}
}
return max;
}
}
Result
app.codility.com/demo/results/training47FHXF-XUU/
Test results - Codility
A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N. For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The
app.codility.com
More Algorithm!
👇👇
github.com/ggujangi/ggu.codility
ggujangi/ggu.codility
[JAVA] Codility Practice. Contribute to ggujangi/ggu.codility development by creating an account on GitHub.
github.com