Created
March 21, 2023 12:36
Codility:BinaryGap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BinaryGap { | |
public int solution(int num) { | |
boolean start = false; | |
int maxZeroCount = 0; | |
int zeroCount = 0; | |
for (; num > 0 ; num = num / 2) { | |
int b = num % 2; | |
if (b == 1 && !start) { | |
start = true; | |
} | |
if (start) { | |
if (b == 0) { | |
zeroCount++; | |
} else { | |
if (zeroCount > maxZeroCount) { | |
maxZeroCount = zeroCount; | |
} | |
zeroCount = 0; | |
} | |
} | |
} | |
return maxZeroCount; | |
} | |
public static void main(String[] args) { | |
int res = new BinaryGap().solution(32); | |
System.out.println(res); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function solution(num) { | |
var start = false; | |
var maxZeroCount = 0; | |
var zeroCount = 0; | |
for (; num > 0 ; num = Math.trunc(num / 2)) { | |
var b = Math.trunc(num % 2); | |
if (b == 1 && !start) { | |
start = true; | |
} | |
if (start) { | |
if (b == 0) { | |
zeroCount++; | |
} else { | |
if (zeroCount > maxZeroCount) { | |
maxZeroCount = zeroCount; | |
} | |
zeroCount = 0; | |
} | |
} | |
} | |
return maxZeroCount; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment