Old Wei wins the offer to take you to learn --- Brush title series (addition, subtraction 48. do not do addition)

48. do not do addition subtraction multiplication and division

problem:

A write function, and the sum of two integers, the function may not be used in vivo requires +, -, *, / four arithmetic symbols.

solve:

thought:

Or two different numbers obtained, but excluding the addition of the carry result, because no bits python limitation, where it is defined in the 32-bit

Two phase number obtained, the addition result into bit digits limits because no python, which is herein defined 32

When there is a carry, it is necessary to continue the addition of the above results. The above operation is repeated until num1 0.

Note: 8-bit value represented in the range -128 to +127, i.e., (100000000-01111111), the first bit is the sign bit.
# 32 so that can be represented in a numerical range 1,000,000,000,000,000 0000 0000 0000 0000 to 0x7FFFFFFF, i.e. to -2147483648 2147483647, but
# is the number of bits python not limitation, i.e., the maximum overflow does not exist, it does not represent the highest negative bit '1' that is the sign bit, it will be 1,000,000,000,000,000 0000 0000 0000 0000 2147483648 considered.
# Perform bounds checking is required, the corresponding negative treatment: ~ (^ num1 0xFFFFFFFF)
return IF num1 num1 <= 0x7FFFFFFF the else ~ (^ num1 0xFFFFFFFF) #python unsigned bitwise right shift operation is not required bounds checking

python code:

# -*- coding:utf-8 -*-
class Solution:
    def Add(self, num1, num2):
        # write code here
        while (num2):
            num1,num2=(num1^num2)& 0xFFFFFFFF,((num1&num2)<<1) & 0xFFFFFFFF
        return num1 if num1<= 0x7FFFFFFF else ~(num1^0xFFFFFFFF)
Published 160 original articles · won praise 30 · views 70000 +

Guess you like

Origin blog.csdn.net/yixieling4397/article/details/105067952