Skip to main content
2 of 5
added 93 characters in body
Vogel612
  • 25.5k
  • 7
  • 59
  • 141

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.

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