371. Sum of Two Integers [easy] (Python)

本文介绍了一种不使用加号和减号计算两个整数之和的方法,通过位操作实现加法,包括按位与、按位异或及进位等步骤,并提供了Python代码示例。

题目链接

https://leetcode.com/problems/sum-of-two-integers/

题目原文

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

Example:
Given a = 1 and b = 2, return 3.

题目翻译

计算两个整数a和b的和,但是不能使用运算符加号和减号。
比如:给定a=1,b=2,返回3。

思路方法

既然不能使用加法和减法,那么就用位操作。下面以计算5+4的例子说明如何用位操作实现加法:
1. 用二进制表示两个加数,a=5=0101,b=4=0100;
2. 用and(&)操作得到所有位上的进位carry=0100;
3. 用xor(^)操作找到a和b不同的位,赋值给a,a=0001;
4. 将进位carry左移一位,赋值给b,b=1000;
5. 循环直到进位carry为0,此时得到a=1001,即最后的sum。

上面思路还算正常,然而对于Python就有点麻烦了。因为Python的整数不是固定的32位,所以需要做一些特殊的处理,具体见代码吧。
代码里的将一个数对0x100000000取模(注意:Python的取模运算结果恒为非负数),是希望该数的二进制表示从第32位开始到更高的位都同是0(最低位是第0位),以在0-31位上模拟一个32位的int。

思路一

迭代求解。

代码

class Solution(object):
    def getSum(self, a, b):
        """
        :type a: int
        :type b: int
        :rtype: int
        """
        while b != 0:
            carry = a & b
            a = (a ^ b) % 0x100000000
            b = (carry << 1) % 0x100000000
        return a if a <= 0x7FFFFFFF else a | (~0x100000000+1)

思路二

递归求解。

代码

class Solution(object):
    def getSum(self, a, b):
        """
        :type a: int
        :type b: int
        :rtype: int
        """
        tmp_a = self.add(a, b)
        return tmp_a if tmp_a <= 0x7FFFFFFF else tmp_a | (~0x100000000+1)

    def add(self, a, b):
        return a if b == 0 else self.add((a ^ b) % 0x100000000, ((a & b) << 1) % 0x100000000)

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.youkuaiyun.com/coder_orz/article/details/52034541

ICPC Asia East Continent Final, one of the oldest, largest, and most prestigious programming competitions in China, is attracting more and more competitors from all over the country to participate in, including CJLUACMers. Moreover, it's a huge dream for most of them. During these years, the EC-Final was always hosted by Northwestern Polytechnical University (NWPU) in Xi'an City, Shann Xi Province. (Reference: http://m.haiwainet.cn/middle/3542417/2019/1218/content_31684163_1.html) As a competitor of ICPC EC-Final in 2019, Derrick took part in this programming competition and visited Xi'an City. However, Derrick had another dream that would be never come true, which was travelling in the ancient Xi'an City in Tang Dynasty. 微信图片_20210307183647(1).jpg In order to discover the landscape of the ancient Xi'an City, Derrick has already searched enough information about it. Just as Hundreds and Thousands of houses are like a Go game, and twelve streets are like a vegetable garden(百千家似围棋局,十二街如种菜畦)written by Juyi Bai. This poetry vividly demonstrates the structure of the ancient Xi'an City, it consists of several vertical streets and horizontal roads of the same lengths but different widths. Supposed that the shape of whole city is an n×n square, which composed of n vertical streets x 1 ​ , x 2 ​ ,..., x n ​ and n horizontal roads y 1 ​ , y 2 ​ ,..., y n ​ within the same lengths and different widths from centre. Derrick is curious about calculating the area of all intersections, because he wants to calculate the traffic flow accurately at each intersection in the ancient Xi'an City. However, Derrick considers this task is quite easy for you, so Derrick will spin the whole square with 45 degree at first, maybe clockwise or maybe counterclockwise. After that, you are asked to calculate the total area of all intersections for each row and each column. Input Specification: There are multiple test cases. The first line of the input contains an integer T, indicating the number of test cases. For each test case: The first line contains two integers n (1≤n≤1000) and d, indicating the size of the square and the direction of rotating the square. When d=1, it means that the direction of rotation is clockwise. When d=0, it means that the direction of rotation is counterclockwise. The second line contains n integers x 1 ​ , x 2 ​ ,..., x n ​ (0≤x i ​ ≤5×10 4 ), indicating the width of vertical streets at the i-th position from centre. The third line contains n integers y 1 ​ , y 2 ​ ,..., y n ​ (0≤y j ​ ≤5×10 4 ), indicating the width of horizontal roads at the j-th position from centre. It's guaranteed that the sum of n of all test cases will not exceed 2×10 4 . Output Specification: For each case, in the first line output 2n−1 integers separated by a space, indicating the total area of intersections for each row after rotating 45 degree. Similarly, in the second line print 2n−1 integers separated by a space, indicating the total area of intersections for each column after rotating 45 degree. Note: Please, DO NOT output extra spaces at the end of each line, or your answer may be considered incorrect! Sample Input: 1 3 0 1 2 3 3 2 1 Sample Output: 3 8 14 8 3 1 4 10 12 9 Hint: For example, the initial state of 3×3 square, the clockwise state of 3×3 square and the counterclockwise state of 3×3 square are shown as the following, respectively: 微信图片_20210307204029.png 代码长度限制 16 KB Java (javac) 时间限制 2000 ms 内存限制 64 MB Python (python2) 时间限制 2000 ms 内存限制 64 MB Python (python3) 时间限制 2000 ms 内存限制 64 MB 其他编译器 时间限制 1000 ms 内存限制 64 MB 栈限制 8192 KB
最新发布
08-31
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值