【问题标题】:How can I increment and decrement an integer with the modulo operator如何使用模运算符递增和递减整数
【发布时间】:2016-04-05 17:01:21
【问题描述】:

我正在尝试根据点击增加一个整数。点击如何发生并不重要,所以我会坚持逻辑。我在 Java 中这样做,但逻辑应该是相同的。

int index = 0;

// then within the click event
//arrySize holds the size() of an ArrayList which is 10

index = (index + 1) % arrySize;

按照这个逻辑,每次用户点击时,index 都会增加 1。然后,当 index 匹配 arrySize 时,arrySize 的模数会导致 index 回到 0

(10 % 10 会使索引回到 0) 这很棒,因为它有点像从 0 到 10 然后回到 0 并且永远不会超过 10 的循环。 p>

我正在尝试执行相同的逻辑,但向后 根据点击,数字将减少并达到 0 然后 回到arrySize 而不是-1

我怎样才能实现这个逻辑?

【问题讨论】:

  • 是的,我知道我可以用一个简单的 if 语句来做到这一点,但想知道是否可以用模数

标签: java increment modulo decrement


【解决方案1】:
(index + arraySize - 1) % arraySize

做你想做的。

【讨论】:

    【解决方案2】:

    从 Java 8 开始,您可以使用 Math.floorMod(x, y) 方法。引用它的 Javadoc(强调我的):

    底模为x - (floorDiv(x, y) * y)与除数y同号,在-abs(y) < r < +abs(y)的范围内。

    System.out.println(Math.floorMod(-1, 5)); // prints 4
    

    所以你将拥有:

    index = Math.floorMod(index - 1, arrySize);
    

    您不能直接拥有-1 % 5,因为这将输出-1 based on how the operator % operates with negatives numbers

    【讨论】:

    • 我明白了,这看起来不错,我要试验一下,然后告诉你。
    【解决方案3】:

    index = arraySize - ((index + 1) % arrySize)

    【讨论】:

      【解决方案4】:

      如果您想要基于 1 的索引,请使用此选项。例如,如果您想倒退到 1 是一月的月份。

      int previous = ((index - 1 - arraySize) % arraySize) + arraySize
      

      结果

      index    previous
      1        12
      2        1
      3        2
      4        3
      5        4
      6        5
      7        6
      8        7
      9        8
      10        9
      11        10
      12        11
      

      Example Fiddle

      【讨论】:

        猜你喜欢
        • 2011-02-16
        • 1970-01-01
        • 1970-01-01
        • 2015-10-03
        • 2014-03-21
        • 1970-01-01
        • 2015-02-16
        • 1970-01-01
        相关资源
        最近更新 更多