Skip to content

Commit

Permalink
Merge pull request apachecn#336 from jiangzhonglian/master
Browse files Browse the repository at this point in the history
更新 9. Palindrome Number 回文数
  • Loading branch information
jiangzhonglian authored May 20, 2020
2 parents 671175a + 598a6fc commit 4ce66dd
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 24 deletions.
3 changes: 0 additions & 3 deletions .gitmodules

This file was deleted.

1 change: 0 additions & 1 deletion Middleware
Submodule Middleware deleted from 65beb9
68 changes: 48 additions & 20 deletions docs/Algorithm/Leetcode/Python/009._Palindrome_Number.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
# 9. Palindrome Number 回文数

**<font color=green>难度: Easy</font>**

## 刷题内容

> 原题连接
* https://leetcode.com/problems/palindrome-number
* https://leetcode-cn.com/problems/palindrome-number

> 内容描述
```
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
Expand All @@ -27,48 +33,70 @@
你能不将整数转为字符串来解决这个问题吗?
```

## 难度:Medium

> 思路1 (满足Follow up)
## 解题方案

- 首先负数肯定不是palindrome
- 其次如果一个数字是一个正数,并且能被我0整除那它肯定也不是palindrome
> 思路1
这样降低了复杂度
* 排除小于0的数
* 通过字符串进行反转,对比数字是否相等就行

```python
class Solution(object):
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0 or (x != 0 and x % 10 == 0):
if x < 0:
return False
rev, y = 0, x
while x > 0:
rev = rev * 10 + x % 10
x /= 10
return y == rev

elif x != int(str(x)[::-1]):
return False
else:
return True


if __name__ == "__main__":
target = 12421
so = Solution()
status = so.isPalindrome(target)
print("结果: ", status)
```


> 思路2
* 排除小于0的数
* 通过字符串进行反转,对比数字是否相等就行
* 数字通过 % 10 求余数进行反转,进而得到最终反转的结果
* 对比反转的结果是最初的结果是否相等

```python
class Solution:
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
elif x != int(str(x)[::-1]):
return False
else:
return True
rev, y = 0, x
while x > 0:
rev = rev * 10 + x % 10
print("余数: %s - 余数反转结果: %s" % (rev, x % 10))
x = int(x/10)
return y == rev


if __name__ == "__main__":
target = 12321
so = Solution()
n = so.isPalindrome(target)
print("结果: ", n)
"""
余数: 1 - 余数反转结果: 1
余数: 12 - 余数反转结果: 2
余数: 123 - 余数反转结果: 3
余数: 1232 - 余数反转结果: 2
余数: 12321 - 余数反转结果: 1
结果: True
"""
```

0 comments on commit 4ce66dd

Please sign in to comment.