首页 > 代码库 > BinaryGap

BinaryGap

Task description

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.

Write a function:

class Solution { public 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.

Assume that:

  • N is an integer within the range [1..2,147,483,647].

Complexity:

  • expected worst-case time complexity is O(log(N));
  • expected worst-case space complexity is O(1).

The obvious solution for this is to convert input integer to its binary representation, and then traverse the generated array to get the maximum number of zeros between ones. But we can also solve without convertion. We know that a zero in a binary number represents a multiple of two, while a one represents a multiple of two with an adder of one. So we can just simply count how many times that this integer can be divided completely between two residus of division by two. So below is the solution:

 1 class Solution { 2     public int solution(int N) { 3         int test =N; 4         int ml =0; 5         int t = 0;         6         boolean power = false; 7         if(test%2==0){ 8             test/=2;  9             power =true;10         }11 12         while(test!=0){13             if(test%2 == 0){14                 if(power){15                     test/=2;16                     continue;17                 }18                 t++;19             }else{20                 power =false;21                 t=0;22             }23             test/=2;24             if(ml<t){25                 ml =t;26             }27         }28         return ml;29     }30 }

The time complexity is O(log(n)) and memory complexity is a constant of O(C).

 

BinaryGap