A + B 问题

A + B 问题

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

注意事项

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

说明

a和b都是 32位 整数么?

  • 是的

我可以使用位运算符么?

  • 当然可以

样例

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

挑战

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

标签

Cracking The Coding Interview 比特位操作

 1 class Solution {
 2 public:
 3     /*
 4      * @param a: The first integer
 5      * @param b: The second integer
 6      * @return: The sum of a and b
 7      */
 8     int aplusb(int a, int b) {
 9         // write your code here, try to do it without arithmetic operators.
10         int result=0,num=0;
11
12         do {
13             result = a ^ b;
14             num = (a & b) << 1;
15             a = result;
16             b = num;
17         }
18         while(b != 0);
19
20         return result;
21     }
22 };
时间: 2024-08-05 08:58:24