BOP - 1的数目

文章后面的扩展问题:

对于二进制,统计1的数目。

f(1)  = 1

f(10) = 10

f(11) = 100

What is f(n)?

 

Analysis:  by different bit

    n (binary)                    f(n) (decimal sum by column)                  

         0  1                                              0   1                              

         1  0                                               1   1                                 

         1  1                                                2  2                               

     1 0  0                                             1 2  2             2 = 2^(3-2)       {3 is the bits of n}                    

     1 0  1                                             2 2  3                                    

     1 1  0                                             3 3  3

     1 1  1                                             4 4  4

  1 0 0  0                                          1 4 4 4              4 = 2^(4-2)

  1 0 0  1                                          2 4 4 5

  1 0 1  0                                          3 4 5 5

  1 0 1  1                                          4 4 6 6

  1 1 0  0                                          5 5 6 6 

  1 1 0  1                                          6 6 6 7

  1 1 1  0                                          7 7 7 7

  1 1  1  1                                          8 8 8 8

1 0 0 00                                        1 8 8 8 8            8= 2^(5-2)      {5 is the bits of n}

Deduction:

For high bit is 1 and the other bits are 0, the numbers of 1 is equal to 1 + (m-1)*(2^(m-2)),

m is the bits of n. And the high bit is ascending order from 1, 

thus the numbers of 1 in the high bit is (n mod 2^m).

 

We can get the formula f(N) = f(N mod 2^m) + 1 + (N mod 2^m) + (m-1)*2^(m-2). {m is the bits of n}

                                            f(1)= 1 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值