Sum of Two Integers
来源:互联网 发布:蛐蛐饲料 淘宝 编辑:程序博客网 时间:2024/05/24 01:54
leetcode第317题,位运算题,在不使用加法和减法的情况下运算加法。
很明显就是一个位运算,首先这样分析,位运算就这么几种,与、或、非、异或、移位。选择哪一种是关键。首先加法肯定要所在位的数值相加,异或可以完成这个功能,但是异或没有进位怎么办,用与操作就可以获取进位值出现在哪一位。但是进位制出现在哪一位,加上这一位进位值的是下一位,因此还需要移位操作。
程序的流程是先进行与操作,提出进位值,然后进行异或,而后将进位值左移,下一次循环的时候,将进位值左移后的数值当做新的加数,知道进位值全部为零了,运算就结束了。
class Solution {public: int getSum(int a, int b) { while(b) { int carry = a & b; a = a ^ b; b = carry << 1; } return a; }};
0 0
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- sum of two integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- 【Leetcode】Sum of Two Integers
- acm学习用的网站
- javascript面向对象 - 理解
- 如何使用KeyChain保存和获取UDID
- Opencv图像识别从零到精通(29)-----图像金字塔,向上上下采样,resize插值
- java中List转数组操作
- Sum of Two Integers
- HTTP中GET与POST的区别
- GBDT(Gradient Boosting Decision Tree) 没有实现只有原理
- 利用fiddler模拟发送json数据的post请求
- cocopods安装过程 报这个错误时候
- 文件是否存在
- viewpager禁止滑动
- 如何正确地写出单例模式
- MyBatis使用简介