【发布时间】:2019-04-23 12:47:40
【问题描述】:
我现在正在处理一个问题,如下所示:
有两个数 x1 和 x2 和 x2 > x1。
例如 x1 = 5; x2 = 10;
我必须在二进制表示中找到 x1 和 x2 之间的和。
5 = 101 => 2 ones
6 = 110 => 2 ones
7 = 111 => 3 ones
8 = 1000 => 1 one
9 = 1001 => 2 ones
10= 1010 => 2 ones
so the sum will be
sum = 2 + 2 + 3 + 1 + 2 + 2 = 12 ones;
所以我设法完成了代码,甚至没有将数字转换为二进制并浪费执行时间。
我注意到每个2^n 和n >= 1 的个数是1
例如:2^1 => num of ones is 1
2^2 => 12^15 => 1
如果你愿意,可以在这里测试:https://www.rapidtables.com/convert/number/decimal-to-binary.html?x=191
每个2^n and 2^(n+1) 之间都有连续的数字,您将在此示例中看到:
num number of ones
2^4 = 16 1
17 2
18 2
19 3
20 2
21 3
22 3
23 4
24 2
25 3
26 3
27 4
28 3
29 4
30 4
31 5
2^5 = 32 1
所以我做了一个代码,可以找到2^n and 2^(n+1)之间有多少个
int t; ////turns
int bin = 1; //// numbers of ones in the binary format ,,, and 1 for 2^5
int n1 = 32; //// 2^5 this is just for clarification
int n2 = 64; //// 2^6
int *keep = malloc(sizeof(int) * (n2 - n1); ///this is to keep numbers because
/// i'll need it later in my consecutive numbers
int i = 0;
int a = 0;
n1 = 33 //// I'll start from 33 cause "bin" of 32 is "1";
while (n1 < n2) /// try to understand it now by yourself
{
t = 0;
while (t <= 3)
{
if (t == 0 || t == 2)
bin = bin + 1;
else if (t == 1)
bin = bin;
else if (t == 3)
{
bin = keep[i];
i++;
}
keep[a] = bin;
a++;
t++;
}
n1++;
}
无论如何,如您所见,我已经接近解决问题,但它们给了我大量的数字,我必须找到它们之间的数字,不幸的是,我尝试了很多方法来使用上面的代码计算“总和”,我结束了解决时间执行问题。
例如:1, 1000000000 the numbers of ones is >>> 14846928141
所以你能不能给我一点提示下一步该做什么,谢谢。
我这样做是为了代码战挑战:https://www.codewars.com/kata/596d34df24a04ee1e3000a25/train/c
【问题讨论】:
-
见Bit Population(中间算法)
-
只要解决 1 和 x 之间有多少个,然后对于 y-x 范围,答案是从 1 到 x - 从 1 到 y。请注意,对于最低有效位,每 2 个数字就会得到一个 1。第二个,每 4 个 2 个,第三个,每 8 个 4 个……
-
在恒定时间内计算它应该是相当简单的(即不循环遍历每个数字)