2014-04-28 22:32

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

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

代码:

 // 17.4 Find the maximum of two numbers without using comparison operator or if-else statement.
// Use bit operation instead. But this solution applies to integer only.
#include <cstdio>
using namespace std; int mymax(int x, int y)
{
static const unsigned mask = 0x80000000;
return (x & mask) ^ (y & mask) ? ((x & mask) ? y : x) : ((x - y & mask) ? y : x);
} int main()
{
int x, y; while (scanf("%d%d", &x, &y) == ) {
printf("%d\n", mymax(x, y));
} return ;
}

最新文章

  1. 15个C++项目列表
  2. Delphi用QJSON解析JSON格式的数据
  3. PHP 知识点链接
  4. CentOS 6.x 系统安装选项说明
  5. 关于spring配置文件properties的问题
  6. 理解python先编译后解释的特点
  7. 启用MySQL查询缓存
  8. 利用 css 制作简单的提示框
  9. Html5 Css实现方形图片 圆形显示
  10. matlab函数:residue和residuez的用法
  11. oracle03
  12. java开发笔记
  13. numpy交换列
  14. cf-Global Round2-C. Ramesses and Corner Inversion(思维)
  15. AngularJs的MVC模式
  16. 连接到win2003的远程桌面,客户端要如何操作
  17. android编译错误“OnClickListener cannot be resolved to a type”
  18. linux下centos7中mysql崩溃问题的解决
  19. gulp使用方法总结
  20. 在临床医学里面,bid、tid、qid和q3w是什么意思啊??这些缩写的全称是怎么写呢??

热门文章

  1. Docker build 安装报错, Could not open requirments file: [Errno 2] No such file or directory:&#39;requirements.txt&#39;
  2. word文档快速转换为PPT演示文稿
  3. CopyTranslator-复制即翻译的外文辅助阅读翻译解决方案
  4. SAP UI5和CRM WebUI的View和Controller是如何绑定的
  5. 打表格,字符串处理,POJ(2136)
  6. python 3+djanjo 2.0.7简单学习(二)--创建数据库和模型
  7. leetCode没那么难啦 in Java (一)
  8. putty乱码问题
  9. Nginx无法加载.woff .eot .svg .ttf等解决办法
  10. get请求中文乱码问题