leetcode371. sum of two integers

约定不等于承诺〃 2022-09-25 06:30 119阅读 0赞

leetcode371. 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.

这个就是基本的加法器(ALU)工作行为。

如果是单比特的a + b,那么结果应该是两位,姑且算是:x1, x0。
x1 = a & b;
x0 = a ^ b;
看看下面的计算表格就知道了:

这个是考虑机器加法所得

  1. int getSum(int a, int b) {
  2. int c = a & b;
  3. int r = a ^ b;
  4. return c == 0 ? r : getSum(r, c << 1);
  5. }

这个是考虑数学

  1. int getSum(int a, int b) {
  2. return (int)log(exp(a)*exp(b));
  3. }

发表评论

表情:
评论列表 (有 0 条评论,119人围观)

还没有评论,来说两句吧...

相关阅读