赞
踩
给你两个整数 a 和 b ,不使用 运算符 + 和 - ,计算并返回两整数之和。
示例 1:
输入:a = 1, b = 2
输出:3
示例 2:
输入:a = 2, b = 3
输出:5
解法:https://leetcode-cn.com/problems/sum-of-two-integers/solution/wei-yun-suan-xiang-jie-yi-ji-zai-python-zhong-xu-y/
(36ms/15MB)
class Solution(object): def getSum(self, a, b): """ :type a: int :type b: int :rtype: int """ # 2^32 MASK = 0x100000000 # 整型最大值 MAX_INT = 0x7FFFFFFF MIN_INT = MAX_INT + 1 while b != 0: # 计算进位 carry = (a & b) << 1 # 取余范围限制在 [0, 2^32-1] 范围内 a = (a ^ b) % MASK b = carry % MASK return a if a <= MAX_INT else ~((a % MIN_INT) ^ MAX_INT)
力扣 (LeetCode)链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-medium/xwaiag/
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。