我有 2 個變數 A 和 B,如果 A =1 那么 B 應該 B=2,如果 A=2 那么 B 應該 B=1 像這樣,有 3 對1-2,3-4,5-6
制作代碼的最佳方法是什么,而不僅僅是 if-else
uj5u.com熱心網友回復:
可以使用簡單的加法和減法來獲得兩者中的另一個元素(x, x 1):
int a = 1; // the other is 2, sum is 3
int b = 3 - a; // if a = 2, b = 1
int c = 3; // the other is 4, sum is 7
int d = 7 - c; // if c = 4, d = 3
int m = 5; // the other is 6, sum is 11
int n = 11 - m;
另一種方法可能是使用以下邏輯:
if (a % 2 == 1) b = a 1;
else b = a - 1;
因此,陣列可用于提供 /- 1:
static int[] signs = {-1, 1};
public static int nextWithArrPositive(int a) {
return a signs [a % 2];
}
a在這種情況下a % 2 == -1,此運算式無法用于負數,并且需要更高級的邏輯來正確計算值以考慮負余數:
public static int nextWithArr(int a) {
int sign = (a & 0x80000000) >> 31; //-1 if a < 0, 0 otherwise
// a >= 0 : 0 - even, 1 - odd;
// a < 0 : 1 - even, 0 - odd
return a signs[a % 2 - sign];
}
但是,可以設計一個更簡單的運算式:
public static int nextWithMod(int a) {
return a a % 2 - (a - 1) % 2;
}
讓我們比較三個實作的結果,包括b = ((a - 1) ^ 1) 1user3386109 在評論中提供的xor 解決方案:
public static int nextXor(int a) {
return ((a - 1) ^ 1) 1;
}
測驗:
System.out.println(" ----- ----- ----- ----- ");
System.out.println("| a | arr | mod | xor |");
System.out.println(" ----- ----- ----- ----- ");
for (int i = -6; i < 7; i ) {
System.out.printf("| - | - | - | - |%n", i, nextWithArr(i), nextWithMod(i), nextXor(i));
}
System.out.println(" ----- ----- ----- ----- ");
輸出:
----- ----- ----- -----
| a | arr | mod | xor |
----- ----- ----- -----
| -6 | -5 | -5 | -7 |
| -5 | -6 | -6 | -4 |
| -4 | -3 | -3 | -5 |
| -3 | -4 | -4 | -2 |
| -2 | -1 | -1 | -3 |
| -1 | -2 | -2 | 0 |
| 0 | -1 | 1 | -1 |
| 1 | 2 | 2 | 2 |
| 2 | 1 | 1 | 1 |
| 3 | 4 | 4 | 4 |
| 4 | 3 | 3 | 3 |
| 5 | 6 | 6 | 6 |
| 6 | 5 | 5 | 5 |
----- ----- ----- -----
uj5u.com熱心網友回復:
一個簡單的解決方案是查表。在aI 的每個可能值的陣列中存盤對應的值b:
private static final int[] B_PER_A = { -1, 2, 1, 4, 3, 6, 5 };
因為在 Java 中陣列索引總是從 0 開始,我們需要在索引 0 處放置一個虛擬值。這個值永遠不會被使用(或者至少應該永遠不會被使用)。
讓我們試試看:
for (int a = 1; a <= 6; a ) {
int b = B_PER_A[a];
System.out.format("a: %d; b: %d.%n", a, b);
}
輸出:
a: 1; b: 2. a: 2; b: 1. a: 3; b: 4. a: 4; b: 3. a: 5; b: 6. a: 6; b: 5.
推廣到超過 3 對
如果您需要處理可變數量的對,請求助于數學。
public static int calcB(int a) {
// 0-based index of pair (0 = 1-2, 1 = 3-4, etc.)
int pairNumber = (a - 1) / 2;
// a b for given pair
int pairSum = 4 * pairNumber 3;
int b = pairSum - a;
return b;
}
在每一對中,總和等于 3 模 4。我正在利用這個事實來找到給定對的總和。當我a從那個總和中減去時,我得到b。讓我們看看也證明了這一點:
for (int a = 1; a <= 8; a ) {
int b = calcB(a);
System.out.format("a: %d; b: %d.%n", a, b);
}
a: 1; b: 2. a: 2; b: 1. a: 3; b: 4. a: 4; b: 3. a: 5; b: 6. a: 6; b: 5. a: 7; b: 8. a: 8; b: 7.
The latter solution is more complicated and harder to read. So if you always have got three pairs, no more, no less, I recommend the simpler table lookup presented first.
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/313572.html
上一篇:我如何為CyclicShift優化此Java代碼(Hackerearth問題)?
下一篇:0/1背包問題的混淆輸出
