Skip to main content
1 of 5
a-ina
  • 315
  • 4
  • 10

BinaryGap - codility

Can I get feedback on my code. This is for the Binary Gap problem. I got 100% in correctness, but I would like to know how can I make it better performance wise. Also, I am not even sure about its complexity and how to make it better. Thanks in advance!

class Solution {
public int solution(int N) {
    // write your code in Java SE 8
    int max = 0;
    boolean flag = false;
    int temp = 0;
    
    //converting number into binary and at the same time checking for max binary gap
    while (N != 0) {
        
        if (N%2 == 1) {
            flag = true;
            if (temp > max) {
                max = temp;
            }
            temp = 0;
        }
        else {
            if (flag) {
                temp++;
            }   
        }
        
        N = N/2;
    }
    
    return max;
}

}

a-ina
  • 315
  • 4
  • 10