# Moderate 不用比较符返回较大的数 @CareerCup

if a and b have different signs:
//  if a > 0, then b <  <d,  and  k = l.
// if a < 0, then b > 0, and k = 0.
// so either way, k = sign(a)
let k = sign(a)
else
let  k  = sign(a  -  b)  //  overflow  is  impossible

int k = use_sign_of_a * sa + use_sign_of_c * sc;

package Moderate;

/**
* Write a method which finds the maximum of two numbers. You should not use if-else or any other comparison operator.

EXAMPLE

Input: 5, 10

Output: 10

*
*/
public class S17_4 {

/* Flips a 1 to a 0 and a 0 to a 1 */
public static int flip(int bit) {
return 1 ^ bit;
}

/* Returns 1 if a is positive, and 0 if a is negative */
public static int sign(int a) {
return flip((a >> 31) & 0x1);
}

public static int getMaxNaive(int a, int b) {
int k = sign(a - b);
int q = flip(k);
return a * k + b * q;
}

public static int getMax(int a, int b) {
int c = a - b;

int sa = sign(a); 		// if a >= 0, then 1 else 0
int sb = sign(b); 		// if b >= 0, then 1 else 0
int sc = sign(c);		// depends on whether or not a - b overflows

/* We want to define a value k which is 1 if a > b and 0 if a < b.
* (if a = b, it doesn't matter what value k is) */

int use_sign_of_a = sa ^ sb; 		// If a and b have different signs, then k = sign(a)
int use_sign_of_c = flip(sa ^ sb); 	// If a and b have the same sign, then k = sign(a - b)

/* We can't use a comparison operator, but we can multiply values by 1 or 0 */
int k = use_sign_of_a * sa + use_sign_of_c * sc;
int q = flip(k); // opposite of k

return a * k + b * q;
}

public static void main(String[] args) {
int a = 26;
int b = -15;

System.out.println("max_naive(" + a + ", " + b + ") = " + getMaxNaive(a, b));
System.out.println("max(" + a + ", " + b + ") = " + getMax(a, b));

a = -15;
b = 2147483647;

System.out.println("max_naive(" + a + ", " + b + ") = " + getMaxNaive(a, b));
System.out.println("max(" + a + ", " + b + ") = " + getMax(a, b));
}
}


## 比较两个数 显示较大的那个数

• 2013年03月13日 16:36
• 6KB
• 下载

## 求较大数的阶乘

• 2008年07月31日 04:26
• 1KB
• 下载

## Zball in Tina Town（数论规律题+特判+较大数判是否为素数的正确姿势）

Link：http://acm.hdu.edu.cn/showproblem.php?pid=5391 Zball in Tina Town Time Limit: 3000/1500 MS (J...

## 从控制台输入三个数，输出较大的那个数（Python）

举报原因： 您举报文章：Moderate 不用比较符返回较大的数 @CareerCup 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)