Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int solution(int N) {
- int longest_binary_gap = -1;
- unsigned int mask = 1 << 31;
- // Find the first occurence of 1
- for (; !(mask & N) && mask != 0; mask >>= 1);
- while (mask != 0) {
- // Move to the next binary digit
- mask >>= 1;
- int current_gap = 0;
- // Count zeroes
- for (; !(mask & N) && mask != 0; mask >>= 1, current_gap += 1);
- // Check if the interval ends with 1 and if it is the longes found so far
- if (mask != 0 && current_gap > longest_binary_gap) {
- longest_binary_gap = current_gap;
- }
- }
- return (longest_binary_gap < 0) ? 0 : longest_binary_gap;
Add Comment
Please, Sign In to add comment