Math.abs() 等 APIif、for、while、switch、? : 等判斷/迴圈==、<=、>=、!=、<、> 等比較運算子public static int abs(int num) {
return num * (1 - ((num >>> 31) << 1));
}
num >>> 31:無符號右移 31 位
01(... << 1):左移 1 位
021 - ...:得到乘數
1-1num * 乘數:正數不變,負數變正 → 絕對值| num | >>31 | <<1 | 1- | 結果 |
|---|---|---|---|---|
| 5 | 0 | 0 | 1 | 5 |
| 0 | 0 | 0 | 1 | 0 |
| -5 | 1 | 2 | -1 | 5 |
| -2147483648 | 1 | 2 | -1 | -2147483648 (溢位) |
Integer.MIN_VALUEMath.abs(Integer.MIN_VALUE) 同樣回傳 -2147483648,因為 32 位有號整數範圍是 [-2^31, 2^31-1],+2^31 無法表示。實務上若需處理此極值,請改用 long 或 BigInteger。
public static void main(String[] args) {
for (int i = -5; i <= 5; i++) {
System.out.println(i + " -> " + abs(i));
}
System.out.println("MIN_VALUE -> " + abs(Integer.MIN_VALUE));
}
此技巧展示位運算替代條件判斷的經典應用,常見於效能敏感、無分支預測的底層程式庫。但現代 JVM JIT 編譯器對 Math.abs 已高度優化,實務開發優先使用標準 API,保持可讀性與正確性。