《程序员代码面试指南》第七章 位运算 不用任何比较判断找出两个数中较大的数

题目

不用任何比较判断找出两个数中较大的数

java代码

package com.lizhouwei.chapter7;

/**
 * @Description: 不用任何比较判断找出两个数中较大的数
 * @Author: lizhouwei
 * @CreateDate: 2018/4/26 21:21
 * @Modify by:
 * @ModifyDate:
*/
public class Chapter7_2 {

    public int getMax(int a,int b){
     int sa = sign(a);
     int sb = sign(b);
     if(sa!=sb){
         return (sa&1)!=1?a:b;
     }
     int sc= sign(a-b);
        return (sc&1)!=1?a:b;
    }
    public int sign(int n){
        return n>>31;
    }

    //测试
    public static void main(String[] args) {
        Chapter7_2 chapter = new Chapter7_2();
        System.out.println("1和2最大为:"+chapter.getMax(1,2));
        System.out.println("1和-2最大为:"+chapter.getMax(1,-2));
    }
}

结果

posted @ 2018-04-26 21:46  lizhouwei  阅读(428)  评论(0编辑  收藏  举报