I. Description of the problem
Calculate the sum of two integers a and b, but you are not allowed to use the operator +
and -
.
Example 1:
Input: a = 1, b = 2
Output: 3
Example 2:
Input: a = -2, b = 3
Output: 1
II. Problem-solving ideas
This question is if you do not have a similar sum ([a, b] such a tricky operation, but truly a local topic and want to visit, you'll find that this question is still a little something.
This question requires an understanding of the underlying computing computer.
When computer numerical calculation in the bottom are a number of first complement representation, and then converted to the source code After computing the return.
Specifically related can refer to this blog.
https://blog.csdn.net/u011240016/article/details/52433355
The most important point is this:
Adder:
Integer: [A] Complement + [B] Complement = [A + B] Complement (mod 2 ^ (n + 1 ))
Decimal: [A] Complement + [B] Complement = [A + B] Complement (mod 2)
Subtraction:
Integer: [AB] Complement = [A] Complement + [-B] Complement (mod 2 ^ (n + 1 ))
Decimal: [AB] Complement = [A] Complement + [-B] Complement (mod 2)
----------------
Disclaimer: this article is the original article CSDN bloggers "DrCrypto", and follow CC 4.0 BY copyright agreement, reproduced, please attach the original source link and this statement.
Original link: https: //blog.csdn.net/u011240016/article/details/52433355
Understood by complement, subtraction is actually addition.
So we just need to implement additions.
It is an addition, phase two numbers to get into position where it is needed,
The two numbers above would like to add a carry results then want to add, the same method of calculating the carry,
Until carry zero.
There are two points where noted:
1.python unlike C ++ Java, the trouble is that in fact there is no numerical limit of the median, worse is the subject did not give number range, based on C ++ situation there should be a 32-bit integer.
2. If the carry note exceeds the 32-bit value overflows description, taken out.
More leetcode algorithm problem solution: Columns leetcode algorithm from zero to the end
III. Source
Reference Code: https://leetcode.com/problems/sum-of-two-integers/discuss/400375/python-methods-%3A-easy-to-understand
class Solution:
#47
def getSum(self, a: int, b: int) -> int:
# Prevent negative number
while b & 0xffffffff: # b & 0xffffffff will remain the same as b with 32 bit
c = a & b
a = a ^ b
b = c << 1
return a & 0xffffffff if b > 0xffffffff else a