论坛首页 Java企业应用论坛

不用判断语句求俩数中的大(或者小)数

浏览 47949 次
精华帖 (0) :: 良好帖 (16) :: 新手帖 (3) :: 隐藏帖 (1)
作者 正文
   发表时间:2010-07-19  
cuishen 写道
severusz 写道
superxielei 写道
int getMaxNum(int a,int b){
  double x = (double)a;
  double y = (double)b;
  return (int)(x/2+y/2+Math.abs(x/2-y/2));
}


双手赞成,想当年老师也是这么讲的!

不能用Math类,看来好多童鞋没有看清题目,就在做了啊!

我把楼上的改成这样了
public static int getMaxNum(int a, int b) {
		double x = (double) a;
		double y = (double) b;
		double temp = x / 2 - y / 2;
		return (int) (x / 2 + y / 2 + ((temp <= 0.0D) ? 0.0D - temp : temp));
	}
0 请登录后投票
   发表时间:2010-08-21  
抛出异常的爱 写道
跳大神也是一种艺术:
public class MaxMin {
	static int max = 0 ;
	public static void main(String[] args) throws InterruptedException {
		MaxMin m = new MaxMin();
		int a = m.max(9, 10);
		System.out.println("最大:"+a);
		
	}
	public int max(int a , int b ) throws InterruptedException{
		new MyThread(a,this).start();
		new MyThread(b,this).start();
		Thread.sleep((a+b));	
		return this.max;
	}
}

class MyThread extends Thread{
	public int f = 0;
	public MaxMin max ;
	MyThread(int f , MaxMin max){
		this.f=f;
		this.max = max;
	}
	public void run() {
		try {sleep(f);} catch (Exception e) {}
		max.max = f;
	}
}

呵呵,a和b的值都很大的时候,等到算出来岂不天荒地老了,还有,a,b中有存在负数的情况呢?
0 请登录后投票
   发表时间:2010-08-22  
呵呵见识了
0 请登录后投票
   发表时间:2010-08-22  
wujiazhao88 写道

前段日子找工作期间,经常上网找面试题目做做。

忘了是哪家公司的题目,其中有这么一道题

说,不能使用boolean,if else等判断语句,要求求出两个数中的大数,

【add at 2009-12-10 15:33:52】另,不能用Math类

 

一开始想来想去没有思路,后来想想,程序中需要判断的不就是if-else等逻辑判断以及异常嘛。。。

既然不能用判断,那就只能用异常了。

所以思路是,构造一段代码,让他遇到两个数时,可以构造出异常。什么代码可以这么神奇呢?

呵呵,很简单,用数组的越界可以解决问题!

 

public static int getMaxValueWidthoutBoolean(int a,int b){
 int[] array=new int[a];
try{
//只要b比a大,数组越界,肯定会导致异常,否则b比a小
//所以在catch模块中返回b,非异常返回a即可
array[b]=0;
}catch(Exception ex){
return b;
}
return a;
}

 呵呵,没去查过别人的解法是咋样的,我觉得应该还有其他更好的解法,各位想一想,知道的告知在下,谢谢了!

各位,好像没说是整数,如果有小数呢?

0 请登录后投票
   发表时间:2010-08-23  
return a > b ? a : b;

兄弟啊能确定这个也不能用吗?
0 请登录后投票
   发表时间:2010-08-23  
这个..能用包装类么?
long i = -1111111111111113L;
long j = -1111111111111112L;
System.out.println(Long.signum(i-j));
0 请登录后投票
   发表时间:2010-08-24  
哈哈,用异常,亏你想的出来~~
0 请登录后投票
   发表时间:2010-08-24  
额,各位同学,咱不挖坟了哈..用移位才是正解,异常其实用的也是if-else
0 请登录后投票
   发表时间:2010-08-24  
public int max(int a , int b)
	{
		Set<Integer> set = new TreeSet<Integer>();
		set.add(a);
		set.add(b);
		return (Integer)set.toArray()[0];
	}

如果觉得Integer不够大,或者比较非整数,可以换成Double。。。
0 请登录后投票
   发表时间:2010-09-03  
呵呵,这个有点意思···
楼主的办法不错···
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics