Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Numbers with Even 1s in Binary

Print numbers whose binary form has an even count of ones. Students use Python bin, slicing, count, and a parity test that differs from even-number testing.

AdvancedPhase 2 - Level 5: Logical Loop CombinationsExample 6 of 12
numbers-with-even-1s-in-binary.py
1# Print numbers
2print("Numbers with even 1s in binary:")
3for num in range(1, 21):
4 # Count 1s in binary
5 binary = bin(num)[2:] # Remove '0b' prefix
6 count_ones = binary.count('1')
7
8 if count_ones % 2 == 0:
9 print(f"{num} (binary: {binary})", end=" ")
10print()

Output

Numbers with even 1s in binary:
3 (binary: 11) 5 (binary: 101) 6 (binary: 110) 9 (binary: 1001) 10 (binary: 1010) 12 (binary: 1100) 15 (binary: 1111) 17 (binary: 10001) 18 (binary: 10010) 20 (binary: 10100)

In this one

  • Read binary text
  • Count set bits
  • Distinguish bit parity from value parity

How it works

  1. 1

    Convert each candidate with bin and remove 0b.

  2. 2

    Count its one characters.

  3. 3

    Print when that count is even.

Edge cases

Does three qualify?

Does three qualify?

Yes. Its binary representation contains two ones.

Does two qualify?

Does two qualify?

No. Binary 10 contains only one one.

What's going on

bin creates binary text with a 0b prefix. The slice [2:] removes that prefix before count('1') counts set bits.

The filter asks whether that count is even, not whether num is even. Three has binary 11, so it qualifies despite being odd. The fixed outer range tests one through twenty and prints each accepted decimal value beside its binary representation.

Does three qualify? Yes. Its binary representation contains two ones.

Does two qualify? No. Binary 10 contains only one one.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does [2:] remove?

Pick an answer to check it.

Question 2

Does three qualify?

Pick an answer to check it.

Questions people ask

Does three qualify?

Yes. Its binary representation contains two ones.

Does two qualify?

No. Binary 10 contains only one one.

What does [2:] remove?

The 0b prefix.