首页 > 其他 > 详细

371. Sum of Two Integers【位运算】

时间:2017-03-27 00:29:20      阅读:241      评论:0      收藏:0      [点我收藏+]

2017/3/16 20:03:07


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、^可以得到哪些bit求和后应该是1。(进位的bit应该变成0,1^1=0)

2、&可以得到哪些bit应该进位

3、由于进位后的bit是1可能和第一步得到的1再次产生进位,所以不断循环,直到不产生进位。

版本1

  1. publicclassSolution{
  2. publicint getSum(int a,int b){
  3. while( b !=0){
  4. int y = a ^ b;
  5. int and =(a & b)<<1;
  6. a = y;
  7. b = and;
  8. }
  9. return a;
  10. }
  11. }
 

371. Sum of Two Integers【位运算】

原文:http://www.cnblogs.com/flyfatty/p/6624796.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!