【问题标题】:Is the check for zero needed in this case (after modulus and addition)?在这种情况下是否需要检查零(在模数和加法之后)?
【发布时间】:2012-05-09 16:10:06
【问题描述】:

如果我有例如int size 并包含例如列表的大小然后具有int distance mod 操作即distance%size(-size - 1) <= distance <= (size - 1)

即距离总是在这个范围内(-size - 1) <= distance <= (size - 1)

如果我对此是正确的,那么CollectionsRotate in JDK 中的以下条件检查是什么意思?

 if (size == 0)
    return;  
 distance = distance % size;  
if (distance < 0)  
   distance += size;  
if (distance == 0)  //Why this check????
    return;     

我在这里可能是错误的或生疏的,但我不认为 distance 在这一点上可能会因为添加而为空。如果列表是0,我们一开始就不会达到那个条件。
那么需要这个条件检查吗?

【问题讨论】:

    标签: java collections int modulo


    【解决方案1】:

    如果distance == n * size (n an int) 那么distance%size == 0。例如distance == 0distance == size

    【讨论】:

    • 在这里,我以为我对所有奇怪的答案都快疯了。很明显,距离在这里很容易为 0。
    • +1 如果 distance == n * size 其中 n 可以是负数或正数,则模数为 0。
    【解决方案2】:

    嗯,有if (distance &lt; 0),但距离也可能是0,因此跳过 distance += size;。因此检查distance == 0

    您也可以使用else if 编写代码:

    //if distance is < 0, distance + size can't be 0 (due to the modulo before)
    //however, distance could be 0 at this point if distance was 0 before or became 0 due to the modulo
    if (distance < 0)  
       distance += size;  
    else if (distance == 0)  //Why this check????
       return; 
    

    【讨论】:

      【解决方案3】:

      如果 size 为 5 且 distance 为 0,则永远不会进行加法,并且在遇到检查时距离将为零。

      【讨论】:

        猜你喜欢
        • 2017-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多