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;
 }
}

Future training - StrSymmetryPoint

Here is another codility problem solution from the codility lessons (StrSymmetryPoint - Find a symmetry point of a string, if any.) 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(String S) {

  // write your code in Java SE 8
  if (S.length() == 1) return 0;
  else if (S.length() == 0 || S.length() % 2 == 0) return -1;
  else {
   int len = S.length();
   int half = (len / 2);
   for (int i = 0; i < half; i++) {
    if (S.charAt(i) != S.charAt((len - 1) - i)) return -1;
   }
   return (len / 2);
  }
 }
}

Future training-OddOccurrencesInArray

Here is another codility problem solution from the codility lessons (OddOccurrencesInArray - Find value that occurs in odd number of elements.) 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");
// XORing any 2 similar number will give us zero 
//Zoring Zero with any number will give us the number
class Solution {
 public int solution(int[] A) {
  // write your code in Java SE 8
  int unPairedNum = A[0];
  for (int i = 1; i < A.length; i++) {
   unPairedNum = unPairedNum ^ A[i];
  }
  return unPairedNum;
 }
}