《Cracking the Coding Interview》——第17章:普通题——题目4
2024-10-20 09:30:51
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 ;
}
最新文章
- 15个C++项目列表
- Delphi用QJSON解析JSON格式的数据
- PHP 知识点链接
- CentOS 6.x 系统安装选项说明
- 关于spring配置文件properties的问题
- 理解python先编译后解释的特点
- 启用MySQL查询缓存
- 利用 css 制作简单的提示框
- Html5 Css实现方形图片 圆形显示
- matlab函数:residue和residuez的用法
- oracle03
- java开发笔记
- numpy交换列
- cf-Global Round2-C. Ramesses and Corner Inversion(思维)
- AngularJs的MVC模式
- 连接到win2003的远程桌面,客户端要如何操作
- android编译错误“OnClickListener cannot be resolved to a type”
- linux下centos7中mysql崩溃问题的解决
- gulp使用方法总结
- 在临床医学里面,bid、tid、qid和q3w是什么意思啊??这些缩写的全称是怎么写呢??
热门文章
- Docker build 安装报错, Could not open requirments file: [Errno 2] No such file or directory:&#39;requirements.txt&#39;
- word文档快速转换为PPT演示文稿
- CopyTranslator-复制即翻译的外文辅助阅读翻译解决方案
- SAP UI5和CRM WebUI的View和Controller是如何绑定的
- 打表格,字符串处理,POJ(2136)
- python 3+djanjo 2.0.7简单学习(二)--创建数据库和模型
- leetCode没那么难啦 in Java (一)
- putty乱码问题
- Nginx无法加载.woff .eot .svg .ttf等解决办法
- get请求中文乱码问题