gpt4 book ai didi

algorithm - 检查循环(模 16)数是否大于另一个?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:40:21 27 4
gpt4 key购买 nike

我有两个以 16 为模的循环整数,因此它们的值介于 0 和 15 之间。

我需要比较两个数字以确定 n_1 是否大于 n_0

n_1 > n_0

很明显,这个没有准确定义,所以我定义n_1如果小于前面8个“数字”则大于n_0,否则小于比 n_0(如果不相等)。

即如果:

n_0 = 0
if n_1 is between 1 and 8 (both inclusive)
then n_1 is greater than n_0.

n_0 = 5
if n_1 is between 6 and 15 (both inclusive)
then n_1 is greater than n_0.

n_0 = 12
if n_1 is between 13 and 15 (both inclusive)
or between 0 and 4 (both inclusive)
then n_1 is greater than n_0.

如何以编程方式表达这种比较?

我肯定我混淆了上面的术语,所以请随时纠正我的措辞。 :)

最佳答案

我在想一个有 16 小时的时钟。这个想法基本上是将 n0 移动到 0 位置并将 n1 移动相同数量的“刻度”。现在您可以简单地检查 n1 是大于还是小于取决于它是在 8 点钟之前还是在 8 点钟之后。

public int compare (int n0, int n1){
int ticksToZero = 16 - n0;
if(n0 == n1)
return 0;
else if((n1 + ticksToZero) % 16 <= 8)
return -1; //n0 is smaller than n1
else
return 1; //n0 is larger than n1
}

关于algorithm - 检查循环(模 16)数是否大于另一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47832475/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com