Miscellaneous problems · Exercise 75 of 100

Count set bits

A set bit is a binary digit whose value is 1. Read the digits from right to left and add one to a running count each time you see a 1. Each digit gets one turn, whatever its place value.

Try it yourself

A sensor reports seven flags as 1011010, with 1 meaning on. How many flags are on?

One-step hint

Read the flags one position at a time. Make a tally mark for each 1, including each member of a run of adjacent 1s.

Worked solution
  1. Read the three rightmost digits from right to left. They are 0, 1, 0, so the count reaches 1.
  2. The remaining digits are 1011. Their three set bits bring the total to 4.
DSA compiler