[leetcode]--371. Sum of Two Integers
来源:互联网 发布:股市行情软件下载 编辑:程序博客网 时间:2024/05/16 00:47
Question 371:
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.
解决思路:求整数和,但是题目说了,不能用算术运算符,所以只能另寻他法。想了半天,或许逻辑运算符可以解决:
1)对两个数据进行与操作,求出对应二进制数据需要进位的位,然后左移一位进位;
2)然后进行亦或操作,求出不需要进位的数据和;
3)循环,判断上面生成的两个数据与操作是否为0 如果为0就循环结束,如果不为0就继续执行上述的重复操作。
解决源码:
package leetcode;import utils.InputUtil;import utils.LogUtil;public class Question371 { public static void main(String[] args) { int a = InputUtil.inputInt("请输入a:"); int b = InputUtil.inputInt("请输入b:"); while( (a&b) != 0){//判断当前a和b相加时是否需要进位:如果还要进位近进入循环否则退出循环. int temp1 = a&b; //与算法,求出要进位的位; temp1 = temp1<<1;//左移一位表示进位. int temp2 = a^b;//亦或求出不需要进位的数据和 a = temp1; b = temp2; } int result = a|b; LogUtil.log_debug(""+result); }}
从上面可以得出结论:
两个整数a和b取与(&)操作:
a&b 的结果是:对应的二进制数据中需要进位的位数;
a^b 的结果是a和b相加之后不需要进位的数据位的和。
0 0
- LeetCode 371. Sum of Two Integers
- 371. Sum of Two Integers LeetCode OJ
- [Leetcode]371. Sum of Two Integers
- LeetCode - 371. Sum of Two Integers
- <LeetCode OJ> 371. Sum of Two Integers
- LeetCode 371. Sum of Two Integers
- leetcode 371. Sum of Two Integers
- leetcode 371.Sum of Two Integers
- LeetCode 371. Sum of Two Integers
- 371. Sum of Two Integers(Leetcode)
- leetcode 371. Sum of Two Integers
- 【leetcode】371. Sum of Two Integers【E】
- [leetcode] 371. Sum of Two Integers
- leetcode.371. Sum of Two Integers
- 371. Sum of Two Integers--LeetCode Record
- LeetCode—371. Sum of Two Integers
- Leetcode 371. Sum of Two Integers
- LeetCode 371. Sum of Two Integers
- 传球游戏-洛谷 1057
- 2.数据的预处理
- [leetCode刷题笔记]2017.02.01
- C#中数组、ArrayList和List三者的区别
- Android studio里搜索不到Genymotion,哪么如何正确的解决这问题尼!!!
- [leetcode]--371. Sum of Two Integers
- 【转】Director 初学教程
- Thread-线程
- windows 安装python3.6(numpy,scipy,pandas,matplotlib,scikit-learn)
- 虚假广告又添新花样,WellBET赞助意甲竟是假!
- Effective Java读书笔记一:并发(66-73)
- vue-cli中配置sass
- 程序的记事本--log4net
- 『 Jack_a_Lent_Notes』---SPI[ATmega128] ②