To commemorate
You are not allowed to use any comparative operations in the function body, such as if, for, while, or call any library function.
int max(int a,int b) { int sa,sb,f; sa=((a/2)&0x80000000)>>31; sb=((b/2)&0x80000000)>>31; f=!(!(a/(b|1))); return (sa^sb)*(a*(!sa)+b*(!sb))+(!(sa^sb))*(a*(sa^f)+b*(!(sa^f))); } int max(int a,int b) { int sa,sb,f; sa=((a/2)&0x80000000)>>31; sb=((b/2)&0x80000000)>>31; f=!(!(a/(b|1))); return (sa^sb)*(a*(!sa)+b*(!sb))+(!(sa^sb))*(a*(sa^f)+b*(!(sa^f)));}
Explanation:
(A/2) & 0x80000000)> 31; // obtain the symbol bit of.
(B/2) & 0x80000000)> 31; // obtain the symbol bit of B.
Unsigned and signed will have an impact on the negative number effect. At that time, this was not taken into account, but it was processed as unsigned number as required by the question.
After dividing by 2, the maximum bit is 0, while the number is still signed.
! (! (A/(B | 1); // The size flag of a and B
A/B, when a is large, it is a non-zero number; otherwise, it is 0, but when B = 0, it cannot be calculated.
Therefore, the minimum position of B is 1 to ensure that the computation can proceed. Although setting 1 will increase the number of low positions to 0 by 1, the result will not be affected.
The opposite result is obtained only to ensure that the result is 1 and 0 instead of other numbers.
The rest is the selective output of logical operations.
A symbol is recorded as Sa
B symbol bits are recorded as Sb
The AB result is compared to f.
There are six cases
Sa <Sb a is a positive number, B is a negative number
Sa> Sb a is negative, B is positive
Sa = Sb AB with the same symbol
Sa = 0 is the same as positive number
Sa = 1 is negative
Sa <Sb, Sa = Sb and Sa = 0 and f = 1, Sa = Sb and Sa = 1 and f = 0 when a is large
Sa> Sb, Sa = Sb and Sa = 0 and f = 0, Sa = Sb and Sa = 1 and f = 1 are larger than B.
Combined output result (Sa ^ Sb) * (*(! Sa) + B *(! Sb) + (! (Sa ^ Sb) * (a * (Sa ^ f) + B *(! (Sa ^ f )));
Remove the intermediate variable.
int max(int a,int b) { return ((((a/2)&0x80000000)>>31)^(((b/2)&0x80000000)>>31))*(a*(!(((a/2)&0x80000000)>>31))+b*(!(((b/2)&0x80000000)>>31)))+(!((((a/2)&0x80000000)>>31)^(((b/2)&0x80000000)>>31)))*(a*((((a/2)&0x80000000)>>31)^(!(!(a/(b|1)))))+b*(!((((a/2)&0x80000000)>>31)^(!(!(a/(b|1))))))); } int max(int a,int b) { return ((((a/2)&0x80000000)>>31)^(((b/2)&0x80000000)>>31))*(a*(!(((a/2)&0x80000000)>>31))+b*(!(((b/2)&0x80000000)>>31)))+(!((((a/2)&0x80000000)>>31)^(((b/2)&0x80000000)>>31)))*(a*((((a/2)&0x80000000)>>31)^(!(!(a/(b|1)))))+b*(!((((a/2)&0x80000000)>>31)^(!(!(a/(b|1)))))));}