Given a base- integer, n, convert it to binary (base-2). Then find and print the base-10 integer denoting the maximum number of consecutive ‘s in ‘s binary representation.
A single integer, n .
Print a single base-10 integer denoting the maximum number of consecutive 1‘s in the binary representation of n.
Sample Input 1
Sample Output 1
Sample Input 2
Sample Output 2
Sample Case 1:
The binary representation of 5 is 101, so the maximum number of consecutive 1‘s is 1.
Sample Case 2:
The binary representation of 13 is 1101, so the maximum number of consecutive 1‘s is 2.
A brief overview on binary numbers:
Binary numbers (base-2) have two digits (0, 1). Decimal numbers (base-10) have 10 digits (0, 1, 2, 3, 4, 5, 6, 7, 8, 9).
To convert a decimal (base-10) number to a binary (base-2) number, follow these steps:
- Divide your base-10 number (quotient) by 2.
- If the dividend is even, the remainder is 0. If it’s odd, the remainder is 1.
- Repeat until your quotient reaches 0. (At each step, your new quotient is quotient/2).
- Write out the binary representation: the last remainder is the first digit in the representation.
No relevant to this problem, but as a side note. To convert binary to decimal, use this example as a guide:
My solution in Ruby:
The hard part of this challenge was getting the maximum occurrence of consecutive 1’s. Looked around stackoverflow and I found that .chunk was my answer.
.chunk is an enumerator that chunks items together based on the value of the block, and return an array of [true,[value]] or [false,[value]].
[Edit] Turns out my solution wouldn’t work for 9, whose binary is 1001. It returned “2” instead of the expected “1” because the solution only accounts for max occurrence of any values, 1 or 0. Here’s Jimmy’s fix:
I also learned the ternary operator, which helps shorten your if/else statement structure. Here’s the format:
if_this_is_a_true_value ? then_the_result_is_this : else_it_is_this