题目:A + B 问题

来源:互联网 发布:vb.net 表格控件 编辑:程序博客网 时间:2024/04/29 12:26

给出两个整数a和b, 求他们的和, 但不能使用 + 等数学运算符。

您在真实的面试中是否遇到过这个题?
Yes
哪家公司问你的这个题?AirbnbAlibaba Amazon Apple Baidu Bloomberg Cisco Dropbox Ebay Facebook Google Hulu Intel Linkedin Microsoft NetEase Nvidia Oracle Pinterest Snapchat Tencent Twitter Uber Xiaomi Yahoo Yelp Zenefits
感谢您的反馈
样例

如果 a=1 并且 b=2,返回3

注意

你不需要从输入流读入数据,只需要根据aplusb的两个参数a和b,计算他们的和并返回就行。

挑战

显然你可以直接 return a + b,但是你是否可以挑战一下不这样做?

说明

a和b都是 32位 整数么?

  • 是的

我可以使用位运算符么?

  • 当然可以
标签 Expand
Cracking The Coding Interview比特位操作
class Solution {    /*     * param a: The first integer     * param b: The second integer     * return: The sum of a and b     */    public int aplusb(int a, int b) {        // write your code here, try to do it without arithmetic operators.        if(b==0){              return a;         }else {               return aplusb(a^b, (a&b)<<1);          }    }};



0 0