作者darkhcv (我只想耍废)
看板Python
标题[问题] 新手解leetcode遇到performance问题
时间Thu Jul 14 17:04:25 2016
最近在练LeetCode题目,因为也有在学python
所以就想说把刚刚用c++解的题目用python写写看
一样的algorithm拿去跑结果出现 "Time Limit Exceeded"
想请教一下为何这样的写法在python下performance会不好?
我用c++写一样的逻辑有通过
class Solution(object):
def getSum(self, a, b):
if (a&b) == 0:
return a|b
while (a&b) != 0:
bit_add = a^b
carry = (a&b) << 1
a = bit_add
b = carry
return a|b
C++版
class Solution {
public:
int getSum(int a, int b) {
if ((a&b) == 0) return a|b;
while ((a&b) != 0) {
int bit_add = a^b;
int carry = (a&b) << 1;
a = bit_add;
b = carry;
}
return a|b;
}
};
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 122.146.84.72
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1468487069.A.360.html
1F:推 tiefblau: C++ code贴一下啊 07/14 17:09
2F:推 Yshuan: python的 & (bit 运算) 费时超过加减法 07/14 17:10
※ 编辑: darkhcv (122.146.84.72), 07/14/2016 17:12:56
3F:→ withoutshine: a=-1, b=1 的时候你的解法似乎是过不了 07/14 20:51
4F:→ darkhcv: a=-1, b=1时,就是会出现"Time Limit Exceeded" 07/14 21:38
5F:→ darkhcv: 我的理解是这个讯息表示跑太久了 07/14 21:39
6F:→ darkhcv: 但是一样的解法以c++来实做是可以测试通过的 07/14 21:39
7F:推 CaptainH: python整数没宽度限制 07/14 23:14
8F:→ CaptainH: 二补数的msb永远是1 当然是无穷回圈 07/14 23:15
9F:推 ckc1ark: -1在python里做bitwise op是0xff....ff无穷多个f 07/14 23:24
11F:→ darkhcv: 了解,谢谢~ 07/15 07:37