Find longest sequence of zeros in binary representation of an integer
ℹ️ © Codility, 2009-2018
Problem
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. The number 32 has binary representation 100000
and has no binary gaps.
Write a function that, given a positive integer n, returns the length of its longest binary gap. The function should return 0 if n doesn’t contain a binary gap.
For example, given n = 1041, the function should return 5, because n has binary representation 10000010001
and so its longest binary gap is of length 5.
Given n = 32 the function should return 0, because n has binary representation 100000
and thus no binary gaps.
Assume that:
• n is an integer within the range [1 … 2,147,483,647].
Complexity:
• expected worst-case time complexity is O(log(n));
• expected worst-case space complexity is O(1).
Solution
C#
using System; class Solution { public int solution(int n) { int r = 0; int t = 0; string S = Convert.ToString(n, 2); foreach (char s in S) { if (s == '1') { if (t > r) { r = t; } t = 0; } else { t++; } } return r; } }
Java
class Solution { public int solution(int n) { int r = 0; int t = 0; String S = Integer.toBinaryString(n); for (int i = 0; i < S.length(); i++) { char s = S.charAt(i); if (s == '1') { if (t > r) { r = t; } t = 0; } else { t++; } } return r; } }
JavaScript
function solution(n) { let r = 0; let t = 0; let S = n.toString(2); for (let i in S) { let s = S[i]; if (s == 1) { if (t > r) { r = t; } t = 0; } else { t++; } } return r; }
PHP
function solution($n) { $r = 0; $t = 0; $S = (string)decbin($n); for ($i = 0; $i < strlen($S); $i++) { $s = $S[$i]; if ($s == 1) { if ($t > $r) { $r = $t; } $t = 0; } else { $t++; } } return $r; }