码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Q371 Sum of Two Integers(Easy)

时间:2016-11-05 11:54:47      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:public   line   sum   color   integer   operator   opera   nbsp   turn   

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。

分析:

  一看题就知道肯定是于位运算有关,很快想到异或,因为只有异或满足单一位的二进制运算(1^1=0,1^0=1,0^1=1,0^0=0)。

  但有一个问题,就是进位。先算出进位的值(就是在异或条件下,比正确答案小的值),然后再相加,直到没有进位。

 

 1 public class Solution 
 2 {
 3     public int GetSum(int a, int b) 
 4     {
 5         int result = a ^ b;
 6         int carry = (a & b) << 1;
 7         if (carry == 0) return result;
 8         return GetSum(result, carry);
 9     }
10 }

 

LeetCode Q371 Sum of Two Integers(Easy)

标签:public   line   sum   color   integer   operator   opera   nbsp   turn   

原文地址:http://www.cnblogs.com/Bita/p/5938530.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!