• + 6 comments

    For all those looking for an explanation, here are some clues for a O(1) solution:

    Lets break down the problem into finding out the 1s in all binary representation of numbers from 0 to n if n is positive and n to -1 if n is negative.

    Lets look at positive numbers. Lets take n = 10. Here is the binary representation of 0 - 10.

    0000
    0001
    0010
    0011
    0100
    0101
    0110
    0111
    1000
    1001
    1010
    

    Look at it column by column. Do you see a pattern? The right extreme least significant bit is 1 alternatively. so for height of column h = n + 1, 1 will be repeated h / 2 times. Now for second column, pattern is 0011. so for column two 1 will be repeated (h / 4)*2 + max(0, (h % 4) - 2) times. Can you generate a formula? we just need to do it for all 32 bits and boom we have the answer!

    Now look at negative numbers. let n = -8. Here are the binary representation from -1 to -8:

    1111
    1110
    1101
    1100
    1011
    1010
    1001
    1000
    

    Can you figure out a similar pattern? this series differs from before only in the fact that hieght will be h = abs(n) and now in every recurring pattern 1 comes before 0. For first column its 1010 and second column its 1100 instead of 0011. Can you come up with another formula?

    Assuming you have cracked both the formula, the problem reduces to this:

    a, b = map(int, input().split())
        if a < 0 and b < 0:
            print(get_one_count_negative(a) - get_one_count_negative(b + 1))
        elif a < 0 and b >= 0:
            print(get_one_count_negative(a) + get_one_count_positive(b))
        elif a == 0:
            print(get_one_count_positive(b))
        else:
            print(get_one_count_positive(b) - get_one_count_positive(a - 1))
    

    Happy Coding!