Cracking the coding interview--Q19.4

1061 ワード

タイトル
原文:
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
訳文:
2つの数の最大値を見つける方法を書きます.if-elseや他の比較操作を使用するべきではありません.
たとえば
入力:5,10
出力:10
に答える
必要なif-elseと比較オペレータを一歩一歩分析することで削除できます.
If a > b, return a; else, return b. If (a - b) < 0, return b; else, return a. If (a - b) < 0,  k = 1; else,  k = 0. return a - k * (a - b).  z = a - b.  k z    ,return a - k * z. 

aがbより大きい場合、a−bは正数であり、最高位は0であり、返されるa−k*z=aである.aがbより小さい場合、a−bは負数であり、最高位は1であり、返されるa−k*z=bである.2つの数のうち大きいものを正しく返すことができます.
また,kはzの最高位(0または1)であり,a,bを1つの配列cで格納し,c[k]に戻ることもできる.
コードは次のとおりです.
class Q19_4{
	public static void main(String[] args){
		System.out.println(findMax(5,9));
	}
	public static int findMax(int a,int b){
		int t=a-b;
		int k=(t>>31)&1;
		return a-k*t;
	}
}

参照先:http://hawstein.com/posts/19.4.html
---EOF---