Archive for August, 2018

I was recently doing Codility tests for practice. I, for once decided that it would be good to practice these things instead of just read them and absorb nothing. The one documented below is the BinaryGap. Essentially the task is find longest sequence of zeros in binary representation of an integer, ignoring those that are not bound on either side with a one.

To explain the code, and why I did what I did.
First thing I did was to convert the integer to a binary string, this was then trimmer as the requirement says you must ignore all trailing spaces “The number 32 has binary representation 100000 and has no binary gaps.” My test case here failed the first time because I didn’t read correctly.

string bits = Convert.ToString(N, 2).TrimEnd('0');

Next thing to do is to decide what we are looking at, and count the occurrence or ignore the occurrence. I initially tried to do this with a switch case, but the interesting thing that I found about the Codility compiler is that it wouldn’t accept

case "0" when count > 0

. So writing this in a switch statement was out of the question. It was that or perhaps just me.

Read Full Article