62,614
社区成员
发帖
与我相关
我的任务
分享
// 10> 取int型变量i的绝对值
public static int getABS(int i) {
int sign = i >> 31;
return (i + sign) ^ sign; // 或 (i ^ sign) - sign
}
public static int abs(int i) {
int mask = i >> 31;
return (mask & (~i + 1)) | (~mask & i);
}
public class Test {
public static void main(String[] args) {
System.out.println(abs(245));
System.out.println(abs(-245));
System.out.println(abs(1234213655));
System.out.println(abs(-1234213655));
System.out.println(abs(0));
System.out.printf("%32s\n", Integer.toBinaryString(0));
System.out.println(Integer.MAX_VALUE);
System.out.println(abs(Integer.MAX_VALUE));
System.out.printf("%32s\n", Integer.toBinaryString(Integer.MAX_VALUE));
System.out.println(Integer.MIN_VALUE + 1);
System.out.println(abs(Integer.MIN_VALUE + 1));
System.out.printf("%32s\n", Integer.toBinaryString(Integer.MIN_VALUE + 1));
}
public static int abs(int val) {
// 看上去是够累的
return (((val & (~0 << 31)) >>> 31) == 1) ? ((~val) + 1) & (~(~0 << 31)) : val;
}
}