length() 的代数方法

Algebraic approach to the length()

假设有一个长度为 5 的字符串对象:

ABCDE

和方法定义:

public int returnIndex(int n)
{
}

当传递给参数的值为 negative 并且计数为 backwards(它应该环绕)时,我如何 return 正确的字符串索引?如果提到的字符串的长度是 5 并且传递的值是 -7 那么它应该 return D 其索引为 3。我试过 Math.abs 但它没有正确计数。 smb 能否让我走上正轨?

您需要同时使用 Math.abs 使数字为正,然后您需要对数字使用取模函数以去除字符串的长度。

请参阅下面的代码。

public static int returnIndex(int n)
{
    String a = "ABCDE";
    n = Math.abs(n) % a.length();
    return a.length() - n;
}

它的作用是取数字,去掉负号,将字符串长度除以 n 后求余数 returns 字符串长度减去 n 的值。

这似乎是您想要的。

正如我在原始评论中所说的那样。

不是 java 问题,更像是数学问题。

模 (%) 运算符解决了大部分 "wrap around" 问题,尽管您仍然需要对负数进行一些调整:

public int returnIndex(int n) {
    String s = "ABCDE";
    int length = s.length();
    int result = n % length;
    if (result < 0) {
        result += length;
    }
    return result;
} 

如果您正在使用 java 8,则可以使用方法 Math.floorMod(int x, int y)
此方法执行环绕作业,甚至适用于负数。

因此您的代码将是:

public int returnIndex(int n) {
        String s = "ABCDE";
        return Math.floorMod(n, s.length());
}