To find the digital hardness of an integer, take its binary representation, and count the number of times both a leading and trailing
1can be removed until it either start or ends with a
0. The total number of bits removed is its digital hardness.
That's quite a wordy explanation - so let's break it down with a worked example.
For this example, we'll use the number 3167. In binary, this is:
(Note that, during the conversion to binary, you should make sure to strip leading zeroes)
It doesn't start or end with
0, so we remove 1 pair of bits:
1 1000101111 1
11 00010111 11
But now there is a 0 at the beginning, so we can't remove anymore
1 pairs. In total, 4 bits we removed, and so 4 is the digital hardness of 3167.
However, for numbers that can be written as 2n-1 for positive n (i.e. contain only
1 in binary representation), 0 will never be reached, and so all the bits can be removed. This means that the hardness is simply the integer's bit length.
You task is to write a program or function which, given a non-negative integer
n >= 0, determines its digital hardness.
You can submit a full program which performs I/O, or a function which returns the result. Your submission should work for values of
n within your language's standard integer range.
Please notify me if any of these are incorrect, or if you'd like to suggest any edge cases to add.
0 -> 0 1 -> 1 8 -> 0 23 -> 2 31 -> 5 103 -> 4 127 -> 7 1877 -> 2 2015 -> 10
Here's the ungolfed Python solution which I used to generate these test cases (not guaranteed to be bug-less):
def hardness(num) -> int: binary = bin(num)[2:] if binary.count('0') == 0: return num.bit_length() revbin = binary[::-1] return min(revbin.find('0'), binary.find('0')) * 2