当前位置:网站首页>不用加减乘除实现加法
不用加减乘除实现加法
2022-07-01 03:13:00 【热心市民薛先生】
此处采用位运算,a+b无进位的结果和a^b相等,0 + 1 = 1 == 0 ^ 1 = 1
a+b的进位等于 (a&b) << 1 3+1的进位为 (11 & 1) << 1 = 10
public int add(int a, int b) {
//进位为0时跳出
while(b != 0){
//进位
int c = (a & b) << 1;
//无进位和
a = a^b;
//进位
b = c;
}
return a;
}
运算3+1:
1 != 0 进入循环 进位c = (11 & 1) << 1 = 10
a = 11 ^ 1 = 10
b = 10第二次循环 10 != 0
c = (10 & 10) << 1 = 100
a = 10 ^ 10 = 0
b = 100第三次循环 100 ! = 0
c = ( 0 & 100) << 1 = 0
a = a ^ 100 = 100
b = 0;结束 结果为 4
边栏推荐
- [machine learning] vectorized computing -- a must on the way of machine learning
- Introduction and basic knowledge of machine learning
- About the application of MySQL
- EDLines: A real-time line segment detector with a false detection control翻译
- JS to find duplicate elements in two arrays
- Install vcenter6.7 [vcsa6.7 (vCenter server appliance 6.7)]
- 雪崩问题以及sentinel的使用
- ECMAScript 6.0
- Metadata in NFT
- Leetcode 1818 absolute value, sorting, dichotomy, maximum value
猜你喜欢
Hal library setting STM32 interrupt
Basic concepts of database
How to achieve 0 error (s) and 0 warning (s) in keil5
【机器学习】向量化计算 -- 机器学习路上必经路
VMware vSphere 6.7 virtualization cloud management 12. Vcsa6.7 update vCenter server license
Cloud native annual technology inventory is released! Ride the wind and waves at the right time
[applet project development -- JD mall] uni app commodity classification page (Part 2)
雪崩问题以及sentinel的使用
Servlet [first introduction]
【Qt】添加第三方库的知识补充
随机推荐
Classic programming problem: finding the number of daffodils
打包iso文件的话,怎样使用hybrid格式输出?isohybrid:command not found
IEDA 右键源码文件菜单简介
LeetCode_ Stack_ Difficulties_ 227. basic calculator (excluding multiplication and division)
Go tool cli for command line implementation
[applet project development -- Jingdong Mall] user defined search component of uni app (Part 1)
JS to find duplicate elements in two arrays
Lavaweb [first understanding the solution of subsequent problems]
STM32 - DS18B20 temperature sampling of first-line protocol
【小程序项目开发 -- 京东商城】uni-app 商品分类页面(下)
Introduction to ieda right click source file menu
别再说不会解决 “跨域“ 问题啦
Subnet division and subnet summary
A few lines of transaction codes cost me 160000 yuan
Edge Drawing: A combined real-time edge and segment detector 翻译
HTB-Lame
Servlet [first introduction]
Huawei operator level router configuration example | BGP VPLS configuration example
POI exports excel and displays hierarchically according to parent-child nodes
Hal library setting STM32 interrupt