Commit 2d7c92a9 authored by whzecomjm's avatar whzecomjm
Browse files

add two problems

parent ec7dbdf2
Loading
Loading
Loading
Loading
+32 −2
Original line number Diff line number Diff line
%% Cell type:markdown id: tags:

# My LeetCode

## 1. twoSum
## 1. 两数之和

以下的方案不能通过 LeetCode 提交,可能原因是全局变量的引入。

%% Cell type:code id: tags:

``` python
class Solution:
    def twoSum(self, nums, target):
        for i in range(len(nums)):
            if target - nums[i] in nums:
                return [i, nums.index(target-nums[i])]

# test
if __name__ == '__main__':
    s = Solution()
    print(s.twoSum([2,8,11,7,15],9))
```

%% Output

    [0, 3]

%% Cell type:markdown id: tags:

## 2. addTwoNumbers
## 2. 两数相加
以下我的方法是针对 List 而非 ListNode. orz

%% Cell type:code id: tags:

``` python
class Solution:
    def addTwoNumbers(self, l1, l2):
        num1 = 0
        for i in range(len(l1)):
            num1 = num1 + l1[i] * 10**(i)
        num2 = 0
        for j in range(len(l2)):
            num2 = num2 + l2[j] * 10**(j)
        nnum = num1+num2
        return [int(x) for x in str(nnum)[::-1]]

if __name__ == '__main__':
    s = Solution()
    print(s.addTwoNumbers([1,2,3],[0,8,4]))
```

%% Output

    [1, 0, 8]

%% Cell type:markdown id: tags:

# 7. 整数反转
使用切片 `[::-1]` 来实现反转整数,最后判定大小溢出。

%% Cell type:code id: tags:

``` python
class Solution:
    def reverse(self, x: int) -> int:
        if x>=0:
            ans = int(str(x)[::-1])
        else:
            ans = -int(str(x)[:0:-1])
        if -2**31 <= ans < 2**31:
            return ans
        else:
            return 0

if __name__ == '__main__':
    s = Solution()
    print(s.reverse(-1236469))
```

%% Output

    -9646321

%% Cell type:code id: tags:

``` python
```