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.
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 I can 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;
}
}