1 / 15

# Count 1s

Count 1s. Solution for HKOI2008 Junior Q3. Problem Description. Every non-negative integer can be written as a sequence of 0s and 1s. Given N, find the number of occurrences of 1s in the binary representation of all integers from 1 to N. e.g. when N= 5,

Télécharger la présentation

## Count 1s

E N D

### Presentation Transcript

1. Count 1s Solution for HKOI2008 Junior Q3

2. Problem Description • Every non-negative integer can be written as a sequence of 0s and 1s. • Given N, find the number of occurrences of 1s in the binary representation of all integers from 1 to N. • e.g. when N= 5, 110=12 210=102 310=112 410=1002 510=1012 So, the answer is 7.

3. Notations • Denote P[m] to be the number of 1s in the binary representation of all integers from 0 to m-1. • Why m-1 instead of m? • Notice that there are exactly m integers from 0 to m-1. • Our goal is to find P when m=N+1. • For example, P[6]=7.

4. Doesn’t seem interesting? Some Interesting Facts

6. Statistics • #Att: 64 • Max: 100 • #Max: 5 • Min: 0 • Std Dev(Att): 29.07 • Mean(Att): 37.97

7. Solution 1 • Brute Force • Iterate from 1 to N, For each integer, Calculate the number of 1s • Time Complexity: O(N log N) • Expected Score: 50

8. Solution 1 • This is an illustration of Solution 1 with N=8 1: 1 1 2: 10 1 3: 11 2 4: 100 1 5: 101 2 6: 110 2 7: 111 3 8: 1000 1 Sum=13

9. Solution 2 • How about we exchange the columns and rows? For simplicity, we write out the zeros. • When m=N+1=9, 0 1 2 3 4 5 6 7 8 bit[3]: 0 0 0 0 0 0 0 0 1 1 bit[2]: 0 0 0 0 1 1 1 1 0 4 bit[1]: 0 0 1 1 0 0 1 1 0 4 bit[0]: 0 1 0 1 0 1 0 1 0 4 Sum=13 • How can we calculate the number of occurrences of 1s for bit[k]?

10. Solution 2 • Observe the periodicity. • For example, bit[1]: 0 01 10 01 10 0 • We can divide them into block of 0s and 1s, where 0-block and 1-block alternates. • The first block must be an 0-block. • The number of bits in each full block = 2k • The number of full blocks = m div 2k • Every block must be full except possibly the last one. • The remaining non-full block has (m mod 2k) bits.

11. Solution 2 • Iterate through all bit positions For each bit[k], calculate number of 1s • Time Complexity: O(log n) • Expected Score: 100

12. Other Approaches • Consider all the integers from 0 to m-1. • For all binary integers ending with ‘0’, if we discard the last bit, we get all integers from 0 to m/2-1. • For all binary integers ending with ‘1’, if we discard the last bit, we get all integers from 0 to m/2-1.

13. Other Approaches • Consider all the integers from 0 to m-1. • Let r= log2m. • For integers from 2r to m-1, if we discard the leading bit, we get all integers from 0 to m-2r-1.

14. Mistakes • What is the total number of possible bit positions?

15. Skills • Binary representation of non-negative integers. • Observation about the periodicity • 64-bit integer

More Related