0

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.

This is the code I come up with,

public int solution(int N) {
    int maxCount = 0;
    boolean foundOne = false;
    while (N > 0) {
        int currCount = 0;
        if(!foundOne && N%2 == 1) {
            foundOne = true;
        }
        while (N > 0 && N % 2 == 0 && foundOne) {
            currCount++;
            N /= 2;
        }
        if (currCount > maxCount) {
            maxCount = currCount;
        }
        N /= 2;
    }
    return maxCount;
}

I need help with analyzing Big O complexity of this code, and also if possible please suggest a O(log(N)) algorithm. Thanks in advance.


Is my code solution for Binary Gap is correct or not? What should I improved in that? have some alternate solutions to binary gap problem, but doesn't include Big O analysis.

phoenix
  • 11
  • 1
  • Stack Overflow is a question-and-answer site, not a homework-writing service. If you think we are going to do/fix your homework for you, then you are sorely mistaken. [An open letter to students with homework problems](https://softwareengineering.meta.stackexchange.com/questions/6166/open-letter-to-students-with-homework-problems) – Joe C Mar 14 '18 at 08:07
  • 1
    As I see you have two loops and each of them has n/2 operations in the worst case. That's why your complexity will be n/2 * n/2 = O(n^2) (we neglect the coefficient 1/4) – statut Mar 14 '18 at 08:10
  • 1
    @statut - The inner loop also shifts `N` so this is really `O(n)` I think. – OldCurmudgeon Mar 14 '18 at 08:19
  • @OldCurmudgeon hm, I missed that. I agree with you. – statut Mar 14 '18 at 08:23
  • 4
    The problem uses the phrase *"a positive integer N"*. Which means that N is a number, e.g. 529. But the algorithm is operating on the bits in the number, which would be 10 bits when N is 529. So the algorithm is already O(logN). – user3386109 Mar 14 '18 at 08:53
  • @JoeC It's not my homework, but I am trying to learn Big O analysis. – phoenix Mar 14 '18 at 11:07
  • 1
    yup,it's logN already – Shihab Shahriar Khan Mar 14 '18 at 11:28

0 Answers0