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

【Leetcode】Sum of Two Integers

时间:2016-06-30 16:31:39      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:https://leetcode.com/problems/sum-of-two-integers/

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

思路:
唉,这题虽然是easy,但是真好烦的一题,之前在hihocoder(还是其他oj)上好像也做过这题? 每次都是模拟32位运算然后遇到负数就搞不定了。。。参考别人的做法。

算法:

     public int getSum(int a, int b) {
       int c = 0;
       while(b!=0){
           c= a^b; //add
           b = (a&b)<<1;//carry
           a =c;
       }
       return a;
    }

【Leetcode】Sum of Two Integers

标签:

原文地址:http://blog.csdn.net/yeqiuzs/article/details/51789987

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