Count Numbers with Even Set Bits
EasyPractice library · +10 XPbit manipulationloopscounting
Given two integers A and B, count how many integers X such that A <= X <= B have an even number of set bits (1s) in their binary representation. The number 0 has zero set bits, which is even.
Input
A single line containing two space-separated integers A and B.
Output
A single integer representing the count of numbers between A and B (inclusive) with an even number of set bits.
Constraints
1 <= A <= B <= 1000
Time limit 1 s (native code; slower languages get more)Memory 256 MB13 hidden tests
Example 1
Input
2 7
Output
3
Numbers are 2(10_2, 1 bit), 3(11_2, 2 bits), 4(100_2, 1 bit), 5(101_2, 2 bits), 6(110_2, 2 bits), 7(111_2, 3 bits). Numbers with even set bits are 3, 5, 6. Count is 3.
Example 2
Input
10 12
Output
2
Numbers are 10(1010_2, 2 bits), 11(1011_2, 3 bits), 12(1100_2, 2 bits). Numbers with even set bits are 10, 12. Count is 2.
Hints
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
Example 1 input
2 7
Example 2 input
10 12