Sum of Two Integers
来源:互联网 发布:恶意百度点击软件 编辑:程序博客网 时间:2024/06/05 08:05
Sum of Two Integers
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example:
Given a = 1 and b = 2, return 3.
思路
不用加减实现求和,有点意思
于是百度发现类似的不用+-*/求a+b的,然后还有a=b*3的
对于b*3的解释是 b*2+b = b=b<<2+b ,都是用位操作
额具体的操作么
找到一个链接了 位运算实现加减乘除
代码
class Solution {public: int getSum(int a, int b) { int carry, add; do { add = a ^ b; carry = (a & b) << 1; a = add; b = carry; } while(carry != 0); return add; }};
解释
可以很容易地用“异或”和“或”操作实现整数加法运算:对应位数的“异或操作”可得到该位的数值,对应位的“与操作”可得到该位产生的高位进位,如:a=010010,b=100111,计算步骤如下:
第一轮:a^b=110101,(a&b)<<1=000100, 由于进位(000100)大于0,则进入下一轮计算,a=110101,b=000100,a^b=110001,(a&b)<<1=001000,由于进位大于0,则进入下一轮计算:a=110001,b=001000,a^b=111001,(a&b)<<1=0,进位为0,终止,计算结果为:111001。
题外话
1 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
- libuv学习笔记(23)
- C语言实现六种排序算法
- 交叉编译环境
- html
- js,jquery常用方法
- Sum of Two Integers
- 贩妖记 > 第七十七章,冲入妖族村落
- 开发环境
- 架构实战-学习笔记
- 求逆元
- leetcode_c++:哈希:Group Anagrams (049)
- java.sql.SQLException: Field 'id' doesn't have a default value解决方案
- 用户需求说明书 与 需求规格说明书 有什么本质区别?
- 关闭eclipse或MyEclipse的单词检查