我闻到作业的味道,所以我省略了代码
一个简单的解决方案,使用对于第 i 个最低有效位的事实,答案将是
(N/2^i)*2^(i-1)+ X
where X = N%(2^i) - (2^(i-1)-1) iff N%(2^i)>=(2^(i-1)-1)
考虑从 1 到 N 的数字的第 i 个最低有效位(基于 1 的索引),然后它们以等于 2^i 的周期重复。在周期中,值的前半部分为 0,下半部分为 1。对于示例:- 对于从 0 到 7 的数字,(0 不会产生任何影响,因此没有效果)
000
001
010
011
100
101
110
111
1st least significant bit = 01010101 Period=2
2nd least significant bit = 00110011 Period=4
3rd least significant bit = 00001111 Period=8
and so on.
So for the ith least significant bit ,answer will be (N/Period)*(Half of Period Size) + (N%(2^i - 1) - Half of Period Size + 1)
The second term will only be taken when N%Remainder is greater than or equal to Half of Period Size.
Also , N%(2^i) can be written as N&(2^i - 1)
礼貌:http ://www.geeksforgeeks.org