Saturday, June 11, 2016

How many numbers in the given interval with a bit set

Problem: given two numbers a and b find how many numbers with a bit x set are there in the interval [a,b].

Example:

Input: 5 8 2

Output: 3

Explanation:

5 = 0101
6 = 0110
7 = 0111
8 = 1000

The second bit (starting from the least significant bit with index 0) is set only in numbers 5, 6 and 7, so there are 3 numbers in the interval [5, 8] with the second bit set.

Solution: