繁体   English   中英

我怎样才能像 Python 代码一样在 Java 中只使用 2 个变量?

[英]How can I only use 2 variables in Java as with the Python code?

这个Python代码也可以写成Java代码吗? :

def gcd(a, b):
    # Return greatest common divisor using Euclid's Algorithm.
    while b:
        a, b = b, a % b
    return a

print (gcd(210, 45))

这是我到目前为止在 Java 代码中的内容:

private static int gcd(int p, int q) {
    // Return greatest common divisor using Euclid's Algorithm.
    int temp;
    while (q != 0) {
        temp = q;
        q = p % q;
        p = temp;
    }
    return p;
}

System.out.println(gcd(210, 45));

如您所见,Java 代码使用了 3 个变量,而 Python 代码仅使用了 2 个变量。 我还想在 Java 代码中只使用 2 个变量,并且我想保留 while 循环并且我不想使用递归。

还有为什么 Java 需要比 Python 代码多 1 个变量? 除了 Python 代码使用元组之外。

两个变量,但你仍然需要交换。

public static int gcd(int r, int s) {
    while (s != 0) {
        r %= s;
        // swap them
        r ^= s;
        s ^= r;
        r ^= s;
    }
    return r;
}

另一种可能性(但不会是 Java)是用byte code编写例程,将其存储在byte[]数组中并作为 Java 方法执行。 如果像Python那样使用内部栈没问题,那么这里应该没问题。

差异的原因是 Python 具有元组创建/分解功能,而 Java 没有。

正如其他答案所提到的,您可以使用异或或加法/减法进行 integer 交换。 然而,我怀疑对于像 C 或 Rust 这样的性能平台来说,这是一种虚假的经济,这种 hack 不会加快速度或减少资源使用。 (不过,如果你只是为了挑战而加入其中,这是合法的,而且可能是唯一的解决方案)

另外,我不认为 Java 允许这个技巧用于更一般的 object 参考。

在每个循环迭代中执行两个步骤并且根本不交换怎么样?

private static int gcd(int p, int q) {
    // Return greatest common divisor using Euclid's Algorithm.
    while (q != 0) {
        p %= q;
        if (p == 0)
           return q;
        q %= p;
    }
    return p;
}

纠正我如果我错了但是,你也可以使用 java 中的 2 个变量进行gcd操作。

private static int gcd(int p, int q) {
    // Return greatest common divisor using Euclid's Algorithm.
    int temp;
    while (p != q) {
        if(p > q)
            p = p - q;
        else
            q = q - p;
    }
    return q;
}

Python 可能在“异或”运算符之上添加了一些合成糖。 这是一种按位运算,可以在不使用临时变量的情况下交换两个不同变量的值。

请参阅下面的 Java 示例:

a = a^b;
b = a^b;
a = a^b;

参见https://en.wikipedia.org/wiki/XOR_swap_algorithm

除了给出的示例之外,还有一个众所周知的算法可以在不使用第三个变量的情况下交换两个 integer 变量ab

// given: two int-variables a and b
a += b;
b = a - b;
a -= b
// result: a and b have been swapped

如果我们现在首先计算a % b并将其分配给a ,那么剩下要做的就是交换ab

// given: two int-variables a and b
a = a % b;
a += b;
b = a - b;
a -= b
// result: the new value of a is b, while the new value of b is a % b

如果加法a + b溢出,这甚至会起作用,因为它会被减法反转。


顺便说一句:我认为这是代码高尔夫。 除非有人受到严重的 memory 约束,否则我不建议使用此解决方案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM