[Codility] Lesson1 - BinaryGap
Task discription
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. The number 32 has binary representation 100000 and has no binary gaps.
Write a function: int solution(int N);
that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap.
For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5. Given N = 32 the function should return 0, because N has binary representation '100000' and thus no binary gaps.
Write an efficient algorithm for the following assumptions:
Source Code
#include <iostream>
#include <algorithm>
#include <stack>
int solution(int N) {
stack<int> s;
// stack의 속성을 이용해 10진수->2진수 변환
while(N > 0) {
int rem = N%2;
s.push(rem);
N /= 2;
}
int cnt = 0, ans = 0;;
int size = s.size();
for(int i=0;i<size;i++) {
// 값을 하나씩 꺼내 BinaryGap 계산
int t = s.top();
s.pop();
if(t == 0) {
cnt++;
}
else {
if(ans < cnt) {
ans = cnt;
}
cnt = 0;
}
}
return ans;
}
Reference
この問題について([Codility] Lesson1 - BinaryGap), 我々は、より多くの情報をここで見つけました https://velog.io/@minwest/Codility-Lesson1-BinaryGapテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol