当前位置:网站首页>【Day_09 0427】 另类加法
【Day_09 0427】 另类加法
2022-08-01 17:40:00 【安河桥畔】
另类加法
题目来源
牛客网: 另类加法
题目描述
给定两个int A和B。编写一个函数返回A+B的值,但不得使用+或其他算数运算符。
示例
输入
1,2
返回
3
思路分析
- 根据位运算来计算得出结果
- 用异或可以表示两数相加没有进位的结果
- 两数向与并左移一位可以表示两数相加进位的情况
- 将异或的结果和相与的结果相加,继续重复上面的步骤进行相加
- 上面的操作可以进行递归调用,递归结束的条件是异或或者相与左移的结果为0
如图,以1+3为例
代码展示
class UnusualAdd {
public:
int addAB(int A, int B) {
if(A==0)
{
return B;
}
if(B==0)
{
return A;
}
//得到相加不进位的结果
int a=A^B;
//得到进位结果
int b=(A&B)<<1;
return addAB(a,b);
}
};
边栏推荐
- 关于单应性矩阵的若干思考
- 存储日报-数据湖架构权威指南(使用 Iceberg 和 MinIO)
- ROS2支持技术:DDS简述
- 金仓数据库 MySQL 至 KingbaseES 迁移最佳实践(2. 概述)
- Xingtu has been short of disruptive products?Will this M38T from the Qingdao factory be a breakthrough?
- 素域和扩域
- Topology Parts Disassembly 3D Visualization Solution
- 快速抽取resnet_v2_152中间的特征层
- Detailed explanation of the working principle of crystal oscillator
- How can become a good architect necessary skills: painting for all the people praise the system architecture diagram?What is the secret?Quick to open this article and have a look!.
猜你喜欢
随机推荐
CodeTON Round 2 (Div. 1 + Div. 2, Rated, Prizes!) Solution
B002 - Embedded Elderly Positioning Tracking Monitor
TCP million concurrent server optimization parameters
【R语言】对图片进行裁剪 图片批量裁剪
插入排序 优化插入排序
【Error】Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘concat’)
理财产品的月年化收益率怎么算?
Detailed explanation of the working principle of crystal oscillator
关于Mysql服务无法启动的问题
云商店携手快报税,解锁财务服务新体验!
gtk显示4通道rgba图像
表达式;运算符,算子;取余计算;运算符优先顺序
QT基础功能,信号、槽
素域和扩域
关于2022年深圳市福田区支持高端服务业发展项目的申报通知
MySQL 45 讲 | 09 普通索引和唯一索引,应该怎么选择?
今年最火爆的词:商业分析,看这一篇就够了!
Unity ui点击事件只响应最上层ui的方式
JumpServer堡垒机部署
Topology Parts Disassembly 3D Visualization Solution









