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

Leetcode:371.Sum Of Two Integer

时间:2017-01-25 13:34:26      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:允许   运算符   font   not   time   log   计算过程   位运算   color   

题目:
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 }

 

 

Leetcode:371.Sum Of Two Integer

标签:允许   运算符   font   not   time   log   计算过程   位运算   color   

原文地址:http://www.cnblogs.com/tmx22484/p/6349327.html

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