Leetcode:371.Sum Of Two Integer

题目:
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进行循环,直到进位为0为止。计算过程与二进制加法器一致。
 
 1 public class Solution {
 2     public int getSum(int a, int b) {
 3         while(b!=0){
 4             int carry = a & b; //计算进位
 5             a = a ^ b;         //计算和数
 6             b = carry<<1;
 7         }
 8         return a;
 9     }
10 }

 

 

posted @ 2017-01-25 12:47  tmx  阅读(148)  评论(0编辑  收藏  举报