Click here to Skip to main content
15,867,686 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone, am trying to solve codility's Binary Gap question BinaryGap coding task - Learn to Code - Codility[^] but my solution is terrible and it would give you headache but i need help to make it work.
My logic is (1) Convert integer N to binary format (2) Store binary format in a character array (3) Loop through character array starting from the left (the end of the character array) and discard any trailing '0s' till we find the first '1'. (4) If the next character after the first '1' is '0', count the number of '0s' till we find another '1'. (5) If there are still some characters in the array, repeat steps 3 and 4, else return the number of '0s' found as binary gap. This logic should work but putting into good concise Java code is my problem. Please my code is terrible and i couldn't complete it, please if it offends you, kindly forgive me, thanks for any help.

What I have tried:

Java
public int solution(int N) {

    int currentGap = 0, largestGap = 0;

    int binaryGap = 0;
    // Convert integer to binary value
    String binaryString = Integer.toBinaryString(N);

    // Put binary value in a charater array
    char [] characters = binaryString.toCharArray();

    // Run a loop starting from the left and check if the characters are 0 or 1
    int j = 0;
    for(int i = characters.length - 1; i < characters.length; i--){
           char c = characters[i];
    // Disregard all trailing zeros till we get to the first 1
        if(c == '1'){
            j++;
        }else if(c == '0'){
            // Needs to delete trailing zeros ?
        }
    }

    // I want to set currentGap to the number of zeros before getting to another 1
    // then repeat the entire process above if there are still characters in the character array

    if(currentGap == largestGap){
        return currentGap;
    }else if(currentGap < largestGap){
        largestGap = binaryGap;
    }
    return binaryGap;
}
Posted
Updated 8-Apr-20 1:49am
v7

I'm on the warpath against Codility right now, so here you go! May it help you!

Here's the way it works:
1) find every gap length
2) sort all the gap lengths
3) return the largest gap length

Quick bit of CS 101 info: Every even number has a binary representation with 0 in the low order bit. Every odd number has a binary representation with 1 in the low order bit. So that means every odd number's low order bit could potentially be the start of a binary gap.

My method works by constantly bit-shifting until I get an odd number. When I get an odd number, I mark that as the start of a binary gap. Then I shift and iterate a counter until I get another odd number. That's the end of the binary gap. I return the counter, then start again.

Once my input number has been shifted all the way to 0, I sort all the gap counts with a good algorithm and return the largest one.

JavaScript
function findBinaryGap(num)
{
	var gapCounts = [];
	
	while (num > 0)
	{
		var isOdd = numberIsOdd(num);
		num = num >> 1;
		if (isOdd)
			gapCounts.push(tallyBinaryGap(num));
	}
	
	gapCounts = quickSort(gapCounts);
	return gapCounts[gapCounts.length - 1];
}

function tallyBinaryGap(num, currentCount)
{
	var tally = 0;
	while (num > 0 && !numberIsOdd(num))
	{
		num = num >> 1;
		tally++;
	}
	return tally;
}

function numberIsOdd(num)
{
	return num & 1;
}

function quickSort(arr)
{
	if (arr.length < 2)
		return arr;

	var midpoint = Math.floor(arr.length / 2);
	var pivot = arr[midpoint];
	var left = [];
	var right = [];
	var duplicates = [];
	
	for (var i = 0; i < arr.length; i++)
	{
		if (arr[i] < pivot)
			left.push(arr[i]);
		
		if (arr[i] > pivot)
			right.push(arr[i]);
		
		if (arr[i] == pivot)
			duplicates.push(arr[i]);
	}
	
	return [...quickSort(left), ...duplicates, ...quickSort(right)];
}
 
Share this answer
 
@OriginalGriff, @Patrice T, thanks a lot.
 
Share this answer
 
Quote:
but my code is TERRIBLE! ! !

Indeed, terrible is the word.
You start with 1 idea (currentGap, largestGap, binaryGap), then switch to another idea in the loop, then come back to first idea when trying to spit out the result.
A complete rewrite is in order.
Advice: Solve the problem by hand, write down how you have done, solve problem again by applying the procedure, change procedure as needed.
When procedure works, it is your algorithm, write code accordingly.

In order to help you understand how your code behave, use the debugger and watch it perform.
-----
Your code do not behave the way you expect, or you don't understand why !

There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your code is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]

http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html[^]
https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]

The debugger is here to only show you what your code is doing and your task is to compare with what it should do.
 
Share this answer
 
That's a terrible solution: it will never be quick, clean, or efficient. Converting a number of a string is a very poor way to start, as it means the system looking at every bit in the input before you even start looking at them!

Instead, look at Java's binary manipulation operators: https://www.vojtechruzicka.com/bit-manipulation-java-bitwise-bit-shift-operations/[^] - specifically the AND, XOR, and the SHIFT operators.

If you want to create a truly efficient method, then have a look here: A C# implementation of AI MEMO 239, Item 169- Count the one bits in a number[^] - it will not do what you want, but it might give you a clue what you can do with an efficient algorithm and bit manipulation ...
 
Share this answer
 
Comments
Maciej Los 8-Apr-20 2:15am    
5ed!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900