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.
packageclass031;
publicclassCode03_GetMax{
// n 0或1
// 0 -> 1 1 -> 0
publicstaticintflip(intn){
returnn^1;
}
// n 任意整数
// n非负的,返回1
// n负的,返回0
publicstaticintsign(intn){
// (n >> 31) & 1 n非负的 0 n负的 1
returnflip((n>>31)&1);
}
publicstaticintgetMax1(inta,intb){
intc=a-b;
intscA=sign(c);// a - b >= 0 scA = 1; a - b <0 scA = 0
intscB=flip(scA);// a - b >= 0 scB = 0; a - b <0 scB = 1
returna*scA+b*scB;
}
publicstaticintgetMax2(inta,intb){
intc=a-b;
intsa=sign(a);// a的符号,非负 1 负 0
intsb=sign(b);// b的符号,非负 1 负 0
intsc=sign(c);// a-b的符号,非负 1 负 0
intdifSab=sa^sb;// 如果不一样,1;如果一样,0
intsameSab=flip(difSab);// 如果一样,1;如果不一样,0
intreturnA=difSab*sa+sameSab*sc;
intreturnB=flip(returnA);
returna*returnA+b*returnB;
}
publicstaticvoidmain(String[]args){
inta=-16;
intb=-19;
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