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 number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps.
입력받은 숫자 N의 이진수에서 1과 1사이의 간격중 가장 긴 것을 구하시오~ 라는걸로 요약이 된다.
풀이는 아래와 같다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | #include <iostream> #include <vector> using namespace std; int solution(int N); int main() { int answer = solution(51712); return 0; } int solution(int N) { int gap = 0; int maxGap = 0; int zero = 0; int isBetween = 0; while (N > 0) { if (N & 1) { isBetween++; if (isBetween == 2) { isBetween = 1; gap = zero; if (maxGap < gap) maxGap = gap; } zero = 0; }else zero++; N >>= 1; } return maxGap; } |
댓글 없음:
댓글 쓰기