Saturday, June 4, 2016

Future training - BinaryGap

Here is another codility problem solution from the codility lessons (BinaryGap- Find longest sequence of zeros in binary representation of an integer.) due to the copy rights I can't copy the content of the problem here so to view the problem description click here.




// you can also use imports, for example:
// import java.util.*;

// you can use System.out.println for debugging purposes, e.g.
// System.out.println("this is a debug message");

class Solution {
 public int solution(int N) {
  // write your code in Java SE 8
  int numberOfGapes = 0;
  int maxGapLength = 0;
  boolean isStartWithOne = false;
  boolean isEndWithOne = false;
  while (N > 0) {
   if (N % 2 == 0) {
    if (isStartWithOne) {
     numberOfGapes++;
    }
   } else {
    if (!isStartWithOne) {
     isStartWithOne = true;
    } else {
     maxGapLength = Math.max(maxGapLength, numberOfGapes);
     numberOfGapes = 0;
    }
   }
   N = N / 2;
  }
  return maxGapLength;
 }
}

No comments:

Post a Comment