当前位置:网站首页>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
边栏推荐
- let const
- Analysis of using jsonp cross domain vulnerability and XSS vulnerability in honeypot
- MySQL主从延迟的解决方案
- Newly found yii2 excel processing plug-in
- AVL balanced binary search tree
- 关于基于kangle和EP面板使用CDN
- Find the original code, inverse code and complement of signed numbers [C language]
- Markdown编辑器Editor.md插件的使用
- 注解@ConfigurationProperties的三种使用场景
- 更改当前文件夹及文件夹下文件日期shell脚本
猜你喜欢
Markdown editor Use of MD plug-in
MySQL主从延迟的解决方案
Explain Huawei's application market in detail, and gradually reduce 32-bit package applications and strategies in 2022
Other 7 features of TCP [sliding window mechanism ▲]
Teach you how to select PCB board by hand (II)
Greenplum 6.x common statements
LeetCode 736. Lisp 语法解析
[Yugong series] February 2022 U3D full stack class 005 unity engine view
【踩坑】nacos注册一直连接localhost:8848,no available server
JS operation
随机推荐
更改当前文件夹及文件夹下文件日期shell脚本
Category of IP address
Tronapi-波场接口-源码无加密-可二开--附接口文档-基于ThinkPHP5封装-作者详细指导-2022年7月6日-新手快速上手-可无缝升级tp6版本
Frequently Asked Coding Problems
Problems encountered in the use of go micro
Other 7 features of TCP [sliding window mechanism ▲]
What is the method of manual wiring in PCB design in 22protel DXP_ Chengdu electromechanical Development Undertaking
Arm GIC (IV) GIC V3 register class analysis notes.
Greenplum 6.x common statements
opencv 将16位图像数据转为8位、8转16
Gson转换实体类为json时报declares multiple JSON fields named
Mountaineering team (DFS)
MySQL主从延迟的解决方案
Upload an e-office V9 arbitrary file [vulnerability recurrence practice]
Enterprise manager cannot connect to the database instance
[Yugong series] February 2022 U3D full stack class 007 - production and setting skybox resources
实现自定义内存分配器
A bug using module project in idea
Quick sorting (detailed illustration of single way, double way, three way)
Pointer advanced, string function