剑指offer65 不用加减乘除做加法【位运算】

题目描述

写一个函数,求两个整数之和,要求在函数体内不得使用 “+”、“-”、“*”、“/” 四则运算符号。

示例:

1
2
输入: a = 1, b = 1
输出: 2

提示:

  • a, b 均可能是负数或 0
  • 结果不会溢出 32 位整数

解题思路

方法一:位运算

异或操作 0^1=1 1^0=1 0^0=0 1^1=0,那么先进行异或操作可以得出不考虑进位的情况
&与操作,可以得出哪一位发生进位,再将进位左移1位后,再与前面的异或操作的结果进行相加操作。直到无进位情况。

代码实现

1
2
3
4
5
6
7
8
9
10
class Solution {
public int add(int a, int b) {
while (b != 0) {
int c = (a & b) << 1;
a = a ^ b;
b = c;
}
return a;
}
}

复杂度分析

时间复杂度:O(1)

空间复杂度:O(1)

资料

剑指offer65 不用加减乘除做加法【位运算】

http://example.com/2021/06/06/剑指offer65-不用加减乘除做加法/

Author

John Doe

Posted on

2021-06-06

Updated on

2021-06-08

Licensed under

You need to set install_url to use ShareThis. Please set it in _config.yml.
You forgot to set the business or currency_code for Paypal. Please set it in _config.yml.

Comments

You forgot to set the shortname for Disqus. Please set it in _config.yml.