2

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.

Write a function:

int solution(int N); 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.

public int solution(int n) {
        // write your code in Java SE 8
        String binaryRep = Integer.toBinaryString(n);
        System.out.println("Binary Representation of " + n + " = " + binaryRep);
        List<String> strList = new ArrayList<String>();
        int count = 0;
        for (int i = 0; i < binaryRep.length(); i++) { // Loop through the each number 
            String str = binaryRep.charAt(i) + ""; // getting one by one number
            if(str.equals("0")){
                for(int j = i;j<binaryRep.length();j++){ //Get each next element
                    String str1 = binaryRep.charAt(j) + "";
                    if(!str.equals("1") &&  str.equals(str1)){
                        if(!strList.isEmpty() && count >= strList.size()){
                            strList.add(str1);
                        }else if(strList.isEmpty()){
                            strList.add(str1);
                        }
                        count ++; 
                    }else{
                        count = 0;
                        break;
                    }
                }
           }   
        }
        return strList.size();
    }
Vimal Panchal
  • 301
  • 1
  • 5
  • 15
  • 1
    Have you tried testing it? – Joe C Dec 03 '16 at 09:44
  • In general your method does work however it does have difficulty with binary strings that end with 0's as with "10100". For this binary string it assumes a gap length of 3 whereas it is a gap length of only 1. So, your method is faulty. – DevilsHnd - 退職した Dec 03 '16 at 11:00

32 Answers32

9

I haven't tested your code yet, but it seems very inefficient if your goal is just counting the longest 'binary gap'.

Problems in your code:

  • Makes java.lang.String when it can be just char. Making objects is much slower than making primitive types.
  • Makes a list when it's able to simply count. As long as you're only going to need size of the list, you can just count it in a integer variable.
  • Stupid algorithm. A substring of a string can't be longer than the original one. I'm talking about the second for loop. For example, let's say you're counting binary gap of 1001. Then your algorithm counts binary gap of 001 and then 01. You don't need to count the second one at all. And it's happening becuase you have two for loops.

The biggest problem is, that it's possible to solve this problem without converting int into java.lang.String at all. And in case you got this problem from a textbook, I believe this is the 'correct' answer: To use bitwise operators.

public static int solution(int num) {
    int ptr; //Used for bitwise operation.
    for(ptr=1; ptr>0; ptr<<=1) //Find the lowest bit 1
        if((num&ptr) != 0)
            break;
    int cnt=0; //Count the (possible) gap
    int ret=0; //Keep the longest gap.
    for(; ptr>0; ptr<<=1) {
        if((num&ptr) != 0) { //If it's bit 1
            ret = cnt < ret ? ret : cnt; //Get the bigger one between cnt and ret
            cnt=-1; //Exclude this bit
        }
        cnt++; //Increment the count. If this bit is 1, then cnt would become 0 beause we set the cnt as -1 instead of 0.
    }
    return ret;
}
quartzsaber
  • 174
  • 3
  • 10
3

This solution does not convert the number to a binary String as that is unnecessary. It looks at each bit from right to left starting with the first bit to the left of the first set bit (1).

n & -n returns a mask with only the rightmost bit of n set. Multiplying that by 2 gives the next bit to the left, which is the appropriate place to start counting.

For each bit check (i.e. each iteration of the loop), it either increments or resets the current counter and uses that to track the maximum contiguous section found so far.

public int solution(int n) {
    int max = 0;
    for (int mask = (n & -n) * 2, current = 0; mask < n; mask <<= 1)
        max = Math.max(max, (n & mask) == 0 ? ++current : (current = 0));
    return max;
}
eattrig
  • 326
  • 1
  • 4
  • 12
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – mufazmi May 21 '21 at 18:23
  • 1
    @mufazmi - fair point. Added an explanation. – eattrig May 21 '21 at 18:48
3

Simplest code from all the above, Codility 100% Correctness and score, Verified!

The solution in Javascript:

function solution(N) {
  let binaryValue = (N >>> 0).toString(2);

  let lengthArr = [];
  let length = 1;

  for(let i = 0; i < binaryValue.length; i++){
    if(binaryValue[i] == 0){
      // Check if 1 is ending then push the lenght to array and reset the length
      if(binaryValue[i + 1] == 1){
        lengthArr.push(length);
        length = 0;
      }

      length++;
    }
  }

  return lengthArr.length ? Math.max(...lengthArr) : 0;

}
Amresh Vs
  • 43
  • 4
2

Here is my Java implementation.

public static int solution(int N) {
    int longestBinaryGap = 0;
    String binary= Integer.toBinaryString(N);
    if(!binary.contains("01")){
        return 0;
    }

    binary = binary.replaceAll("0*$", "");
    String[] gaps = binary.split("1");


    for (String g:gaps) {
        if(g.length()>longestBinaryGap){
            longestBinaryGap = g.length();
        }
    }

    return longestBinaryGap;
}
Mwas
  • 153
  • 2
  • 6
  • 17
2

A one-liner in Python: Task Score 100%, Correctness 100%

def solution(N):
    b=bin(N)[2:]
    return len(max(b.strip('0').split('1'))) 
# here strip will remove all trailing 0's and split will create a list with splitting 1's and combining 0's which are together.
Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44
1

There is no need to place the contents of the binary string into an Array (unless of course this is a requirement), simply iterate through the string itself and use the String.substring() method to retrieve the string represented value of each binary digit, as in:

String digit = binaryString.substring(i, i+1);

It all boils down to counting the number of 0's between any set of 1's and keeping track of those 0's by using a Integer data type variable that is incremented every time a 0 is encountered. This same variable is reset to 0 every time a 1 is encountered but before it's reset you would compare it to yet another predefined Integer variable which would hold the longest run of 0's encountered, for example:

if(binaryString.substring(i, i+1).equals("1")) {
    if (zeroHit > longest) { longest = zeroHit; }
    zeroHit = 0;
}
else { zeroHit++; }

The whole method might look something like this:

private static int solution(int intValue) {
    String binaryString = Integer.toBinaryString(intValue);
    int zeroHit = 0;
    int longest = 0;
    for (int i = 0; i < binaryString.length(); i++) {
        if(binaryString.substring(i, i+1).equals("1")) {
            if (zeroHit > longest) { longest = zeroHit; }
            zeroHit = 0;
        }
        else { zeroHit++; }
    }
    return longest;
}
DevilsHnd - 退職した
  • 8,739
  • 2
  • 19
  • 22
1

Here is my modest solution. Now I see that it's looks like modification of DevilsHnd answer. I tested it

public int countZeros(int n) {
        String binaryRep = Integer.toBinaryString(n);
        char[] nChars = binaryRep.toCharArray();
        int nElemLength = Math.min(binaryRep.lastIndexOf('1') + 1, nChars.length);
        if (nElemLength <= 2) {
            return 0;
        }
        String[] elementsParts = binaryRep.substring(0, nElemLength).split("1");
        int zeroLength = 0;
        for (String elementsPart : elementsParts) {
            if (elementsPart.length() > zeroLength) {
                zeroLength = elementsPart.length();
            }
        }
        return zeroLength;
    }
BlackRainbow
  • 1,754
  • 1
  • 13
  • 10
1

What about this algorithm. Is it bad for time performance or good?

int count = 0, prevCount = 0;

while (a > 1) {

  if (a % 2 == 0) {
     count++;
     if (count > prevCount)
        prevCount++;
     } else {
            count = 0;
        }    
        a = a/2;
    }

    if(a % 2 == 0)
       prevCount++;
Hafiz Waleed Hussain
  • 1,062
  • 12
  • 25
1

OBJECTIVE-C SOLUTION O(2n)

Results given by Codility

Task Score: 100%
Correctness: 100%
Performance: Not assesed

Time Complexity

The worst case time complexity is O(2n)

Algorithm Explanation

FACTS

Every valid gap starts with a '1' and close with another '1', with at least one 'zero' between them.

  • 1001 - Is a valid gap
  • 00100 - Isn't a valid gap
  • 10100 - Is a valid gap
  • 11111 - Isn't a valid gap

STEP 1

  • Get the bits of n, using an auxiliary method wich has O(n) Complexity

STEP 2

  • Iterate over each bit we got in Step One
  • Start looking for the first '1' - since our flag 'hasStartPattern' is false in the first iteration, we'll look for the first occurrence of '1', that means we have a valid start pattern and we change the flag 'hasStartPattern' to true for the next iterations we should validate if the current bit is '0' and use a counter, in this case 'candidates'.
  • Only if, there is another '1' in the incoming bits, we are sure that we have a valid binary gap, then we compare our previous 'candidates' with our current 'gapCounter' in order to keep the highest one.
  • In case that there isn't another '1' to close the gap, we never change the value of 'gapCounter' and we return 0.

Xcode Solution Here

+(int)solutionTwo:(int)n {    
    // STEP 1
    // O(n)
    NSString *bits = [self getBitsForNumber:n];

    BOOL hasStartPattern = NO;
    int candidates = 0;
    int gapCounter = 0;

    // STEP 2
    // O(n)
    for (int i=0; i < bits.length; i++) {

        char currentBit = [bits characterAtIndex:i];

        if ( hasStartPattern  && currentBit == '0' ) {
            candidates++;
        }
        else if ( hasStartPattern  && currentBit == '1' ) {
            // At least one '1' exist as a close pattern
            if (candidates > gapCounter) {
                gapCounter = candidates;
            }
            candidates = 0;
        }
        else if (currentBit == '1') {
            hasStartPattern = YES; // At least one '1' exist as an open pattern
        }

    }

    return gapCounter;
}

/*
Time Complexity:
- The worst case time complexity for this auxiliary method is O(n)
*/
+(NSString*)getBitsForNumber:(int)n {
    NSMutableString *bits = [NSMutableString string];
    while(n) {
        [bits insertString:((n&1)? @"1" : @"0") atIndex:0];
        n /= 2;
    }
    return bits;
}
1

This is the C# code equivalent

 public int solution(int N) {
    // write your code in C# 6.0 with .NET 4.5 (Mono)
    int m;
    for (m=1;m>0;m<<=1){
        if((m&N) !=0){
        break;
        }
    }
    int i = 0;
    int j = 0;
    for (; m>0;m<<=1){
        if((m&N) !=0){
            j=i<j ? j:i;
            i=-1;
        }
        i++;
    }
    return j;
    }
}
  • The question was flagged Java. – François B. Nov 06 '20 at 20:41
  • 2
    @FrançoisB. I was searching for this same question's solution in C# but didn't see it so it could be useful for somebody using C# as there are other answers here using other programming language like scala and PHP. – Kehinde Ogundeyi Nov 07 '20 at 09:06
1

Here's a possible solution for the Binary Gap in Java 11 (codility test)

class Solution {
    public int solution(int N) {
        // write your code in Java SE 11
        String binN= Integer.toBinaryString(N);
         
        int counter=0;
        int maxCount=0;
        
        boolean enableCounter=false;
        char prevChar= binN.charAt(0);

        for(int i=1 ; i < binN.length()-1; i++){
            if(prevChar=='1'){
                enableCounter=true;
            }
            
            if (binN.charAt(i)=='0' && enableCounter){
                counter++;
                            
                if (binN.charAt(i+1)=='1'){
                   if(counter>maxCount){
                       maxCount=counter;
                   } 
                    counter=0;
                }
            }
            prevChar=binN.charAt(i);
        }
        
        return maxCount;
    }
}
Miguel Tomás
  • 1,714
  • 1
  • 13
  • 23
1

Here's a working code 100% in swift :)

public func solution(_ N : Int) -> Int {
    let str = String(N, radix: 2)
    if str.contains("1") && str.contains("0") {
        if str.split(separator: "0").count != 1 {
            if str.last == "0" {
                return str.split(separator: "1").dropLast().max()!.count
            }
            return str.split(separator: "1").max()!.count
        }
    }
    return 0
}
Kiki Sasha
  • 29
  • 2
0

I think your code is a little bit confusing,check this one.

public int solution(int n) {
    if (n <= 0) return 0;
    char[] chars = Integer.toBinaryString(n).toCharArray();
    ArrayList<Integer> arrayList = new ArrayList<>();
    int maxCount = 0;
    for (int i = 0; i < chars.length; i++) {
        while (chars[i] == '0' && i + 1 < chars.length) {
            maxCount++;
            i++;
            if (i + 1 == chars.length && chars[i] == '0')
                maxCount = 0;
        }
        if (maxCount != 0)
            arrayList.add(maxCount);
        maxCount = 0;
    }

    return arrayList.isEmpty() ? 0 : Collections.max(arrayList);
}
0

Hi this is my solution for this task. I had Task Score : 100% Correctness : 100%

public int solution(int N) {
    String binary = Integer.toBinaryString(N);
    int[] table = new int[binary.length()];

    for (int i=0;i<binary.length();i++){
        int number = Integer.parseInt(binary.substring(i,i+1));
        table[i] = number;
    }

    int resu = 0;
    int res = 0;
    for (int i=0;i<table.length;i++){
        if (table[i] == 1){
            if (resu > res){
                res = resu;
            }
            resu = 0;
        }else {
            resu++;
        }
    }

    return res;
}
0

For the benefit of all, here is my solution to the Binary Gap which got me 100% for both Task Score and Task Correctness:

class Solution {
    public int solution(int N) {
        String nStr = Integer.toBinaryString(N);

        boolean isCounting = false;
        int j=0;
        int[] seqs = new int[32];
        for (int i=0; i<nStr.length(); i++)
        {
            if ( nStr.charAt(i) == '1')
            {
                if (!isCounting)
                {
                    isCounting = true;
                    seqs[j] = 0;
                }
                else // isCounting, turn it off
                {
                    isCounting = false;
                    j++;
                }

            }
            else // nStr.charAt(i) == '0'
            {
                if (!isCounting)
                    isCounting = true;
                seqs[j]++;
            }

        }
        if (isCounting == true)
            seqs[j] = 0;

        int maxGap = 0;
        for (int k=0; k<seqs.length; k++)
            if (seqs[k] > maxGap)
                maxGap = seqs[k];
        return maxGap;
   }
}
Very Objective
  • 601
  • 7
  • 16
0

OBJECTIVE-C SOLUTION O(n)

Results given by Codility

Task Score: 100%
Correctness: 100%
Performance: Not assesed

Time Complexity

The worst case time complexity is O(n)

Algorithm Explanation

FACTS

Every valid gap starts with a '1' and close with another '1', with at least one 'zero' between them.

  • 1001 - Is a valid gap
  • 00100 - Isn't a valid gap
  • 10100 - Is a valid gap
  • 11111 - Isn't a valid gap

STEP 1

  • Get bits representation one by one from the Rigth to the Left.

  • That means, for n=4, I'll get first a Zero, then another Zero, then a One, finally a Zero. [0,1,0,0]

  • 4 -> 0100

STEP 2

  • Start looking for the first '1' - since our flag 'hasStartPattern' is false in the first iteration, we'll look for the first occurrence of '1', that means we have a valid start pattern and we change the flag 'hasStartPattern' to true for the next iterations we should validate if the current bit is '0' and use a counter, in this case 'candidates'.

  • Only if, there is another '1' in the incoming bits, we are sure that we have a valid binary gap, then we compare our previous 'candidates' with our current 'gapCounter' in order to keep the highest one.

  • In case that there isn't another '1' to close the gap, we never change the value of 'gapCounter' and we return 0

Xcode Solution Here

-(int)solutionOne:(int)n {

    BOOL hasStartPattern = NO;
    int candidates = 0;
    int gapCounter = 0;

    while(n){
        // STEP 1
        NSString *bit = (n & 1) ? @"1": @"0";
        n /= 2;

        // STEP 2
        if ( hasStartPattern  && [bit isEqualToString:@"0"]) {
            candidates++;
        }
        else if ( hasStartPattern  && [bit isEqualToString:@"1"]) {
            // At least one '1' exist as a close pattern
            if (candidates > gapCounter) {
                gapCounter = candidates;
            }
            candidates = 0;
        }
        else if ([bit isEqualToString:@"1"]) {
            hasStartPattern = YES; // At least one '1' exist as an open pattern
        }
    }
    return gapCounter;
}
0

I think this one is a very small code

    public int solution(int N)
    {
        string binary = Convert.ToString(N, 2);
        binary = binary.TrimEnd(new Char[] { '0' });
        var gaps = binary.Split('1');
        int max = 0;
        foreach (var item in gaps)
        {
            if (!string.IsNullOrEmpty(item))
                if(item.Length > max)
                   max = item.Length;
        }            
        return max ;
    }
user1445018
  • 117
  • 1
  • 6
0

here mine

public int solution(int N) {

    String binary = Integer.toBinaryString(N);

    LinkedList<Integer> gaps = new LinkedList<>();
    int countGap = 0;
    int j = 0;
    for (int i = 1; i < binary.length() - 1; i++) {
        if (binary.charAt(i) == '0') {
            countGap++;
        } else {

            gaps.add(j, countGap);
            j++;
            countGap = 0;
        }
    }

    gaps.add(j, countGap);

    if (binary.charAt(binary.length() - 1) == '0') {
        gaps.set(gaps.size() - 1, 0);
    }

    Collections.sort(gaps);

    return gaps.getLast();
}
0

Here is my solution. (Scala)

It is 100/100.

 object Solution {
  def solution(n: Int): Int = {
   val regex = raw"(?=(10*1))".r
   val result = regex.findAllMatchIn(n.toBinaryString).map(_.group(1)) match {
    case re:Iterator[String] if !re.isEmpty => (re.toList.map(Integer.parseInt(_, 2)).sorted.last.toBinaryString.length - 2)
    case _ => 0
  }
  result
  }
}
BrsAtmn
  • 3
  • 1
  • 8
0

My solution using JavaScript, tested 100%.

function solution(N) {
    N = N.toString(2);
    let numberOfOnes = 0;
    let binaryGap = 0;
    let binaryZeros = 0;
    for(let i=0; i<N.length; i++) {
        if(N[i] > 0) {
            numberOfOnes++;
        }
    }
    if(numberOfOnes) {
        for(let j=0; j<N.length; j++) {
            if(N[j] > 0) {
                if(binaryZeros) {
                    if(binaryZeros > binaryGap) {
                        binaryGap = binaryZeros;
                    }
                }
                binaryZeros = 0;
            }
            if(N[j] < 1) {
                binaryZeros++;
            }
        }
    } else {
        binaryGap = 0;
    }
    return binaryGap;
}
Chigozie Orunta
  • 448
  • 3
  • 13
0

I adapted @minary solution with PHP and it worked.

  function maxZeros($N){
    $ptr = 0; //Used for bitwise operation.
     for($ptr = 1; $ptr > 0; $ptr <<= 1) //Find the lowest bit 1
      if(($N & $ptr) != 0)
        break;

    $cnt = 0; //Count the (possible) gap
    $ret = 0; //Keep the longest gap.
     for(; $ptr > 0; $ptr <<= 1) {
      if(($N & $ptr) != 0) { //If it's bit 1
        $ret = $cnt < $ret ? $ret : $cnt; //Get the bigger one between cnt and ret
        $cnt = -1; //Exclude this bit
      }
      $cnt++; //Increment the count. If this bit is 1, then cnt would become 0 because we set the cnt as -1 instead of 0.
     }
    return $ret;
   }

  //Run the function below, for example N = 32
   $N = 32; 
   echo (maxZeros($N)); 
Union
  • 1
  • 1
  • 2
0

Here is mine wrote in Javascript, can someone critic this, it scored 100% though on Codility.

const binaryGap = (intN)=>{
    const binary = Array.from(intN.toString(2)).map(item=>parseInt(item))
    
    const newArrayGroup = []

    const arrLength = binary.length

    let zeroGroup = []

    for (let index = 0; index < arrLength; index++) {

        const parsedInt = binary[index]

        if ( parsedInt == 0 ) {

            zeroGroup.push(parsedInt)   
        }else{
            if (zeroGroup.length>0) {
                newArrayGroup.push(zeroGroup.length)
            }
            zeroGroup = []
        }
    }

    return newArrayGroup.length == 0 ? 0 : Math.max(...newArrayGroup)
}

0

Here is my answer in C#:

class Solution {
    public int solution(int N) {
        // write your code in C# 6.0 with .NET 4.5 (Mono)
         string Nbin = Convert.ToString(N, 2);
            string[] arr = Nbin.Split('1');
            int maxZ = 0;
            if (arr.Length > 2 && arr[arr.Length - 1] == " ")
            {
                foreach (var item in arr)
                {
                    if (item.Length > maxZ)
                    {
                        maxZ = item.Length;
                    }
                }
            }
            else
            {
                for (int i = 0; i < arr.Length - 1; i++)
                {
                    if (arr[i].Length > maxZ)
                    {
                        maxZ = arr[i].Length;
                    }
                }
            }
            return maxZ;
    }
}
0

This is my simple solution

class Solution {
    public int solution(int N) {
        // write your code in Java SE 8
        String b = Integer.toBinaryString(N);

        char[] binaryArr = b.toCharArray();
        int max = 0;
        int internalCount = 0;
        for(int index=1; index< binaryArr.length; index++){
            if(binaryArr[index] =='0')
                internalCount++;
            else{

                if (max<internalCount) max = internalCount;
                internalCount =0;

            }
        }


        return max;
    }
}
Nesrin
  • 395
  • 3
  • 8
0

Here is my short solution in PHP (Task Score: 100%, Correctness: 100%)

function solution($N) {
    $gaps = array();
    $s = explode('1', trim(decbin($N),'0'));
    foreach($s as $g){
        $gaps[] = strlen($g);
    }
    return max($gaps);
}
RainMaker
  • 41
  • 3
0

For Javascript Here is my solution.

function solution(N){
      N = N.toString(2);
      var totalOnes = 0;
      var binaryGap = 0;
      var binaryZero = 0;
      const foundBinaryZero = []

      for(let i=0; i<N.length; i++) {
        if(N[i] > 0) {
            totalOnes++;   
            foundBinaryZero.push(binaryZero);
            binaryZero = 0;
           
        }else{
            binaryGap = 0;
            binaryZero = binaryZero + 1;
          
        }
    }

    foundBinaryZero.sort();


    return (foundBinaryZero[foundBinaryZero.length - 1]);

}
Sujan Mhrzn
  • 147
  • 1
  • 5
0

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.

Hi everyone, I have just solved this problem, hope fully it will help you all.

    public int solution(int N) {
          
        String toBinary = Integer.toBinaryString(N);
        char[] ch = toBinary.toCharArray();
        int maxCount = 0;
        int count = 0;
        boolean flag = false;
          
        for(int i=0; i < ch.length; i++){
            if(ch[i] == '1'){
                if(count > maxCount){
                 maxCount = count;
                }
             count = 0;
            } else
              count ++;
        }
         return maxCount;
    }
}
0

I added this solution and the Codility score is 100%.

public int solution(int N) {
    String s = Integer.toBinaryString(N);
    s = removeTrailingZeros(s);
    System.out.println(s);
    String arrayBinary[] = s.split("1");
    int x = 0;
    for (String abc : arrayBinary) {
        if (abc.length() > x)
            x = abc.length();
    }
    return x;
}

private String removeTrailingZeros(String s) {
    if (s.endsWith("0")) {
        s = s.substring(0, s.length() - 1);
        return removeTrailingZeros(s);
    }
    return s;
}

Executed test sets

Vinod
  • 1
0

If binary number ends with 0 then number % 2 == 0 otherwise number % 2 == 1, using this rule we can solve it very easily.

def solution(N: int):
  prev = 0
  current = 0
  
  # remove leading zeros
  while N % 2 == 0:
    N >>= 1

  # shift to right until its reaches 1
  while N != 1:
  
    if N % 2 == 0:
      current += 1
    else:
      prev = max(current, prev)
      current = 0

    N >>= 1
  return max(prev , current)
Naqib Hakimi
  • 874
  • 4
  • 15
0

In PHP

function solution($N) {
 $bin = decbin($N);
 $gap = [];
 $len = strlen($bin);
 $startCount = 0;
 $endCount = 0;

 $startCount = strpos($bin,'0');

 if(! $startCount)
     return 0;

 while($startCount){
     $endCount = strpos($bin,'1',$startCount);
    
     if(! $endCount)
         break;

     $sub = substr($bin,$startCount,$endCount - $startCount);
     array_push($gap,strlen($sub));
    
     $startCount = strpos($bin,'0',$endCount);   
 }

 $sum = 0;
 if(count($gap)>0)
     return max($gap);
 else
     return 0;
}
Waad Mawlood
  • 727
  • 6
  • 10
0

Below is my solution in Java. Task score , correctness=100%

class Solution {
    public int solution(int N) {
        // Implement your solution here
        int maxGap=0;
        boolean patternStarts=false;
        boolean patternEnds=false;
        int countZero=0;
        int startIndex=0;
        int endIndex=0;
        String binary=Integer.toBinaryString(N);
        for(int i=0;i<binary.length()-1;i++){
            if(binary.charAt(i)=='1' && binary.charAt(i+1)=='0'){
                patternStarts=true;
                startIndex=i+1;

            }
            if(patternStarts && binary.charAt(i+1)=='1'){
                patternEnds=true;
                endIndex=i;
                maxGap++;
                int count=endIndex-startIndex+1;
                countZero=Integer.max(count,countZero);
                patternStarts=false;patternEnds=false;
            }      
        }
        return countZero;
    }
}
LinFelix
  • 1,026
  • 1
  • 13
  • 23
-1

here is my solution.

It is 100/100.

I think it can be polished though.

    class Solution {
      public int solution(int N) {

       String s = Integer.toBinaryString(N);
       int ctr = 0;

       for (int x = 0; x < s.length(); x++){

           if (s.substring(x,x+1).equals("1")){

               ctr++;
           }

       }


       int result[] = new int[ctr];

       boolean flag = false;
       int fCtr = 0;
       for(int y = 0; y < s.length(); y++){
           if(s.substring(y,y+1).equals("1")){
               flag = true;
               if(flag == true){
                    fCtr++;
               }

               }
           else if (s.substring(y,y+1).equals("0") && flag == true && fCtr < ctr){
               result[fCtr]++;
           }
         } 

        int ans = 0;
        for (int d = 0; d < result.length; d++){
            if (ans <= result[d]){
                ans = result[d];
            }
        }

       return ans;
    }
}
Sanpas
  • 1,170
  • 10
  • 29