Computers represent numbers in base 2, not base 10. In base 2, the digits (from right to left) represent powers 20 21, 22, 23, ... The digits in a number are only allowed to be 0 or 1. For example, 1012 = 1×22 + 0×21 + 1×20 = 510. The following table shows a few numbers written in base 10 (decimal) and base 2 (binary).
Decimal | Binary | |
---|---|---|
1 | 1 | |
3 | 11 | |
4 | 100 | |
6 | 110 | |
10 | 1010 | |
15 | 1111 | |
16 | 10000 |
This problem is similar to the preceding problem, but this time the idea is to count how many of the bits in a binary number are 1. Call the function numOneBits(n). For example, numOneBits(5) = 2 since 510 is written 1012 in base 2, and two of the digits are 1. Similarly, numOneBits(15) = 4 since 1510 is written 11112 in base 2.
(Note. n `mod` 2 is the rightmost bit of n (written in binary) and n `div` 2 is what you get by removing the rightmost bit. For example, (11011112) `mod` 2 = 1 and (11011112) `div` 2 = (1101112).)
Test your definition by pushing the Compute button. After it works, submit it by pushing the Submit button.