我正在处理一个问题,它如下所示:
有两个数字x1和x2,其中x2 > x1。
例如,x1 = 5; x2 = 10;
我必须找到在x1和x2之间的二进制表示中1的总和。
我成功地编写了一段代码,甚至没有将数字转换为二进制并浪费执行时间。
我注意到在每个
所以我编写了一段代码,可以找到在
无论如何,正如您所看到的,我已经接近解决这个问题,但他们给了我巨大的数字,我必须找到它们之间的数字,不幸的是,我尝试了很多方法来使用上面的代码计算“总和”,但最终遇到了时间执行问题。
例如:
我正在为CodeWar挑战做这个: https://www.codewars.com/kata/596d34df24a04ee1e3000a25/train/c
有两个数字x1和x2,其中x2 > x1。
例如,x1 = 5; x2 = 10;
我必须找到在x1和x2之间的二进制表示中1的总和。
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的数量是1
。
例如:2^1 => 数字1的数量为1
2^2 => 1
2^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和2^(n+1)
之间有多少个数字是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 数字中1的数量为 >>> 14846928141
那么,您能否给我一点提示下一步该怎么做呢?提前感谢您。我正在为CodeWar挑战做这个: https://www.codewars.com/kata/596d34df24a04ee1e3000a25/train/c