zoukankan      html  css  js  c++  java
  • 《Cracking the Coding Interview》——第17章:普通题——题目4

    2014-04-28 22:32

    题目:不用if语句或者比较运算符的情况下,实现max函数,返回两个数中更大的一个。

    解法:每当碰见这种无聊的“不用XXX,给我XXX”型的题目,我都默认处理的是int类型。最高位是符号位,用x - y的符号位来判断谁大谁小。请看下面代码,条件表达式配合异或运算能满足题目的要求。

    代码:

     1 // 17.4 Find the maximum of two numbers without using comparison operator or if-else statement.
     2 // Use bit operation instead. But this solution applies to integer only.
     3 #include <cstdio>
     4 using namespace std;
     5 
     6 int mymax(int x, int y)
     7 {
     8     static const unsigned mask = 0x80000000;
     9     return (x & mask) ^ (y & mask) ? ((x & mask) ? y : x) : ((x - y & mask) ? y : x);
    10 }
    11 
    12 int main()
    13 {
    14     int x, y;
    15     
    16     while (scanf("%d%d", &x, &y) == 2) {
    17         printf("%d
    ", mymax(x, y));
    18     }
    19     
    20     return 0;
    21 }
  • 相关阅读:
    Linux内核编译
    Linux系统启动流程(2)
    Linux系统启动流程及grub重建(1)
    shell函数
    css基础
    前端之练习抽屉首页
    css简单分页
    mysql索引提高查询速度
    html基础
    博客园css样式代码
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3698141.html
Copyright © 2011-2022 走看看