You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1.5 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package class021;
public class Code02_GetMax {
// 输入参数n一定要保证n不是1就是0
// n == 0 -> 1
// n == 1 -> 0
public static int flip(int n) {
return n ^ 1;
}
// 输入参数n可以是任何一个整数
// 如果n是非负数返回1(int)
// 如果n是负数返回0(int)
public static int sign(int n) {
return flip((n >> 31) & 1);
}
// a和b中谁大返回谁
public static int getMax1(int a, int b) {
int c = a - b;
int scA = sign(c); // c >= 0 scA = 1; c < 0 scA = 0
int scB = flip(scA);
return a * scA + b * scB;
}
public static int getMax2(int a, int b) {
int c = a - b; // c是a-b的差值有可能溢出也有可能不溢出
int sa = sign(a); // a的符号求出a>=0 1, a<0 0
int sb = sign(b); // b的符号求出b>=0 1, b<0 0
int sc = sign(c); // c的符号求出c>=0 1, c<0 0
// 如果a和b的符号不一样difSab == 1
// 如果a和b的符号 一样difSab == 0
int difSab = sa ^ sb;
// 如果a和b的符号一样sameSab == 1
// 如果a和b的符号不一样sameSab == 0
int sameSab = flip(difSab);
int returnA = difSab * sa + sameSab * sc;
int returnB = flip(returnA);
return a * returnA + b * returnB;
}
public static void main(String[] args) {
int a = -16;
int b = 1;
System.out.println(getMax1(a, b));
System.out.println(getMax2(a, b));
a = 2147483647;
b = -2147480000;
System.out.println(getMax1(a, b)); // wrong answer because of overflow
System.out.println(getMax2(a, b));
}
}