当前位置:网站首页>Several methods of calculating the average value of two numbers
Several methods of calculating the average value of two numbers
2022-07-07 08:52:00 【Please Sit Down】
Method 1 : Directly find the average ( Add two numbers and divide by two )
int average(int x,int y){
return (x + y) / 2;
}
This algorithm has some defects , When x and y When large enough x and y And there will be data overflow , So we can't get the result we want .( It is not recommended to use )
Method 2 :x + y And x Divide by 2 And , Data overflow can be avoided
int average(int x,int y){
return x + (y - x) / 2;
}
Method 3 : Improvement method version II ( Displacement )
int average(int x,int y){
return x + ((y - x) >> 1);
}
Method four : Using bit operations - Intersection plus half of difference ( Rounding down )
int average(int x,int y){
return (x & y) + ((x ^ y) >> 1);
}
Method five : Using bit operations - Intersection plus half of difference ( Rounding up )
int average(int x,int y){
return (x | y) - ((x ^ y) >> 1);
}
Method four 、 V see link : The magic of bit operation - Find the average of two integers - You know
边栏推荐
- LeetCode 715. Range module
- Teach you how to select PCB board by hand (II)
- let const
- [Chongqing Guangdong education] accounting reference materials of Nanjing University of Information Engineering
- Database storage - table partition
- Data analysis methodology and previous experience summary 2 [notes dry goods]
- 测试踩坑 - 当已有接口(或数据库表中)新增字段时,都需要注意哪些测试点?
- 使用AGC重签名服务前后渠道号信息异常分析
- 数字三角形模型 AcWing 275. 传纸条
- Greenplum 6.x monitoring software setup
猜你喜欢
平台化,强链补链的一个支点
[Nanjing University] - [software analysis] course learning notes (I) -introduction
【MySQL】数据库进阶之触发器内容详解
Rapid integration of authentication services - harmonyos platform
最长上升子序列模型 AcWing 1017. 怪盗基德的滑翔翼
指针进阶,字符串函数
Greenplum 6.x common statements
Quick sorting (detailed illustration of single way, double way, three way)
What is the method of manual wiring in PCB design in 22protel DXP_ Chengdu electromechanical Development Undertaking
Upload an e-office V9 arbitrary file [vulnerability recurrence practice]
随机推荐
Frequently Asked Coding Problems
Redis fault handling "can't save in background: fork: cannot allocate memory“
Required String parameter ‘XXX‘ is not present
路由信息协议——RIP
String operation
LeetCode 736. LISP syntax parsing
【踩坑】nacos注册一直连接localhost:8848,no available server
LeetCode 715. Range module
IP地址的类别
Mountaineering team (DFS)
LeetCode 715. Range 模块
数据分析方法论与前人经验总结2【笔记干货】
Required String parameter ‘XXX‘ is not present
cmake命令行使用
如何统计项目代码行数
[Yu Yue education] higher vocational English reference materials of Nanjing Polytechnic University
Skills that testers must know: Selenium's three waiting ways are interpreted clearly
Qt Charts使用(重写QChartView,实现一些自定义功能)
Sign and authenticate API interface or H5 interface
Greenplum 6.x common statements