/* * @lc app=leetcode.cn id=371 lang=c * * [371] 两整数之和 * * https://leetcode-cn.com/problems/sum-of-two-integers/description/ * * algorithms * Easy (55.04%) * Total Accepted: 8.1K * Total Submissions: 14.8K * Testcase Example: '1\n2' * * 不使用运算符 + 和 - ,计算两整数 a 、b 之和。 * * 示例 1: * * 输入: a = 1, b = 2 * 输出: 3 * * * 示例 2: * * 输入: a = -2, b = 3 * 输出: 1 * */ int getSum(int a, int b) { if(a && b) return getSum(a^b, (a&b) << 1); else return a|b; }
这里对a和b进行二进制上的相加,然后递归中处理进位。
(不过这里一直会溢出。。。。。。尴尬)
-------------------------------------------------------------------------
python:
# # @lc app=leetcode.cn id=371 lang=python3 # # [371] 两整数之和 # # https://leetcode-cn.com/problems/sum-of-two-integers/description/ # # algorithms # Easy (55.04%) # Total Accepted: 8.1K # Total Submissions: 14.8K # Testcase Example: '1\n2' # # 不使用运算符 + 和 - ,计算两整数 a 、b 之和。 # # 示例 1: # # 输入: a = 1, b = 2 # 输出: 3 # # # 示例 2: # # 输入: a = -2, b = 3 # 输出: 1 # # class Solution: def getSum(self, a: int, b: int) -> int: while b != 0: carry = a & b a = (a ^ b) % 0x100000000 b = (carry << 1) % 0x100000000 return a if a <= 0x7FFFFFFF else a | (~0x100000000+1)
这里模拟32位的int 左移位,python左移位是不会溢出的。