Skip to content
DeepForgeby svx
All problems
EasyAlgorithmsal-320

Ruler Function

Problem

Return the first n values of the ruler sequence for the integers 1 through n, where the i-th value is the exponent of the largest power of two that divides i.

So 1 gives 0, 2 gives 1, 4 gives 2, 8 gives 3 and odd numbers give 0. Return an empty list for n <= 0.

Hint

i & -i isolates the lowest set bit, whose bit length minus one is the exponent.

Test cases

case 1
in: [0]
expected: []
case 2
in: [1]
expected: [0]
case 3
in: [4]
expected: [0,1,0,2]
case 4
in: [8]
expected: [0,1,0,2,0,1,0,3]
case 5
in: [16]
expected: [0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4]
Starter codePython
def ruler_function(n):
    # Your code here
    pass

5 test cases · run your code against them in the editor