leetcode371 Sum Of Integers 不用加法计算两个整数的和
来源:互联网 发布:linux漏洞列表 编辑:程序博客网 时间:2024/05/22 02:07
Description
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.
解法
思路:
首先不能用”+”、” - “符号,那么计算两个数的和也就只能用“位运算符”。位运算符是处理二进制数的,先想想十进制的怎么进行加法的。
比如3+18=21。 首先个位相加3+8 = 11,个位是1,有进位。进位再与十位相加得到十位是2。
二进制也一样,如果不考虑进位,那么1+0=1、1+1=0、0+0=0 这个结果是和“异或”(^)位运算符的处理结果是一样的。之后处理进位问题,有且仅有1+1的情况下才会产生进位,所以用“&”位运算符来处理进位情况,运算之后向左移一位(<<)即可。
代码:
public int getSum(int a, int b) { if(b == 0) return a; return getSum(a^b, (a&b)<<1); }
0 0
- leetcode371 Sum Of Integers 不用加法计算两个整数的和
- LeetCode371——Sum of Two Integers(不用+)
- leetcode371: Sum of 2 Integers
- leetcode371. sum of two integers
- leetcode371-----Sum of Two Integers
- Leetcode371: Sum of Two Integers
- Leetcode371.Sum of Two Integers
- leetcode371:Sum of Two Integers
- leetcode371. Sum of Two Integers
- leetcode371. Sum of Two Integers
- LeetCode371. Sum of Two Integers
- LeetCode 371. Sum of Two Integers不用加减实现加法
- leetcode 371. Sum of Two Integers(不用+ -实现加法)
- 371 Sum of Two Integers用位操作实现两个数的加法——递归
- 371. Sum of Two Integers, 不用加减乘除运算符计算两数之和
- 计算两个1000位大整数的加法
- leetcode 371. Sum of Two Integers 位运算 + 加法操作
- 【leetcode74】Sum of Two Integers(不用+,-求两数之和)
- PHP常用函数(4)json_decode(),json_encode()
- hdu 1230&&九度oj 1016 火星A+B
- Android系统字体
- android studio运行android项目时出现错误return code 1 for dex解决办法
- Flume NG之Agent部署和sink配置HDFS
- leetcode371 Sum Of Integers 不用加法计算两个整数的和
- ElasticSearch的基本用法与集群搭建
- JSON字符串与JSON对象的相互转换(在JavaScript和Java中)
- 在一个数组中找到三元组,使得三元组内的三个元素加和为0。
- android.os.TransactionTooLargeException
- Mvc动态注册HttpModule详解
- 错误-Android-OpenCV-It seems that your device does not support camera(or it is locked)
- HLS学习(六)HLSDownloader源码分析(5)解析Media PlayList
- vagrant2