当前位置:网站首页>【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);
}
};
边栏推荐
猜你喜欢

史上最全的Redis基础+进阶项目实战总结笔记

实现mnist手写数字识别

The site is not found after the website is filed. You have not bound this domain name or IP to the corresponding site! The configuration file does not take effect!

QLineEdit learning and use

04 flink cluster construction

缓存一致性MESI与内存屏障

程序员架构修炼之道:如何设计“易理解”的系统架构?

浅谈游戏音效测试点

面经汇总-社招-6年

QT_QThread thread
随机推荐
tooltip 控件
QLineEdit learning and use
今年最火爆的词:商业分析,看这一篇就够了!
插入排序 优化插入排序
【R语言】对图片进行裁剪 图片批量裁剪
【TDP加码福利】COS用户实践征文月,等你来投稿!!!
Basic image processing in opencv
Detailed explanation of the working principle of crystal oscillator
golang json returns null
实现mnist手写数字识别
Pytorch|GAN在手写数字集上的复现
解决MySQL插入不了中文数据问题
opencv语法Mat类型总结
块级元素、行内元素、行内块元素
百度网盘下载速度提升100倍
RecSys'22|CARCA: Cross-Attention-Aware Context and Attribute Recommendations
我在启牛开户安全吗?谁能告诉我开不靠谱?
【Error】Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘concat’)
md5sum源码 可多平台编译
【100个网络运维工作者必须知道的小知识!】