[英]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;
除了給出的示例之外,還有一個眾所周知的算法可以在不使用第三個變量的情況下交換兩個 integer 變量a
和b
:
// given: two int-variables a and b
a += b;
b = a - b;
a -= b
// result: a and b have been swapped
如果我們現在首先計算a % b
並將其分配給a
,那么剩下要做的就是交換a
和b
:
// 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.