My experience on my daily works... helping others ease each other

Thursday, January 9, 2020

Codility - Find longest sequence of zeros in binary representation of an integer.

I'm taking the coding test at Codility for a job offered by a Japanese company (of which I did not get it). For practice, I tried all and this are the code (in Java) for binary gap

public int solution (int N){
//Convert the value to binary and split the value between number 1
        String s2[] = Integer.toBinaryString(N).substring(0, Integer.toBinaryString(N).lastIndexOf('1') ).split("1");
        int x = 0;
        int a = 0;
        
//find and count the longest zeros
        while(x < s2.length){
            a = a > s2[x].length() ? a : s2[x].length();
            x++;
        }
        
        System.out.println("Number: " + N + System.lineSeparator() + "Binary: " + Integer.toBinaryString(N) 
                + System.lineSeparator() + "Zero: " + a);
        return a;
    };

It score 100% for codility test.

You can download the code here
Bitbucket - git clone https://masteramuk@bitbucket.org/fullstacksdev/codility-binarygap.git
Github - git clone https://github.com/masteramuk/codility-lessoncode.git
Share:

0 comments:

About Me

Somewhere, Selangor, Malaysia
An IT by profession, a beginner in photography

Blog Archive

Blogger templates