[LeetCode] 009. Palindrome Number (Easy) (C++/Java/Python)
2015-03-01 10:13
405 查看
索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)
Github: https://github.com/illuz/leetcode
代码(github):https://github.com/illuz/leetcode
可以先转为字符串,再判断。(这种解法用 Python 可以一句话完成 =w=)
更好的方法是直接算出回文的数再直接比较。
Python:
C++:(算出回文)
Java:
Python:
Github: https://github.com/illuz/leetcode
009.Palindrome_Number (Easy)
链接:
题目:https://oj.leetcode.com/problems/palindrome-number/代码(github):https://github.com/illuz/leetcode
题意:
判断一个数是否是回文数。分析:
按自己想的去写就行了。可以先转为字符串,再判断。(这种解法用 Python 可以一句话完成 =w=)
更好的方法是直接算出回文的数再直接比较。
代码:
C++:(可以先转为字符串)class Solution { public: bool isPalindrome(int x) { if (x < 0) return false; int bit[10]; int cnt = 0; while (x) { bit[cnt++] = x % 10; x /= 10; } for (int i = 0; i < cnt; i++) if (bit[i] != bit[cnt - i - 1]) return false; return true; } };
Python:
class Solution: # @return a boolean def isPalindrome(self, x): return str(x) == str(x)[::-1]
C++:(算出回文)
class Solution { public: bool isPalindrome(int x) { long long xx = x; long long new_xx = 0; while (xx > 0) { new_xx = new_xx * 10 + xx % 10; xx /= 10; } return new_xx == (long long)x; } };
Java:
public class Solution { public boolean isPalindrome(int x) { long xx = x; long new_xx = 0; while (xx > 0) { new_xx = new_xx * 10 + xx % 10; xx /= 10; } return new_xx == x; } }
Python:
class Solution: # @return a boolean def isPalindrome(self, x): xx = x new_xx = 0 while xx > 0: new_xx = new_xx * 10 + xx % 10 xx /= 10 return new_xx == x
相关文章推荐
- [LeetCode] 020. Valid Parentheses (Easy) (C++/Java/Python)
- [LeetCode] 014. Longest Common Prefix (Easy) (C++/Java/Python)
- [LeetCode] 006. ZigZag Conversion (Easy) (C++/Java/Python)
- [LeetCode] 013. Roman to Integer (Easy) (C++/Java/Python)
- [LeetCode] 007. Reverse Integer (Easy) (C++/Java/Python)
- [LeetCode] 008. String to Integer (Easy) (C++/Java/Python)
- LeetCode 63 — Unique Paths II(C++ Java Python)
- LeetCode 21 — Merge Two Sorted Lists(C++ Java Python)
- LeetCode题解汇总(C++ Java Python,含题目翻译)
- LeetCode 15 — 3Sum(C++ Java Python)
- LeetCode 69 — Sqrt(x)(C++ Java Python)
- LeetCode 142 — Linked List Cycle II(C++ Java Python)
- LeetCode 2 — Add Two Numbers(C++ Java Python)
- LeetCode 136 — Single Number(C++ Java Python)
- LeetCode 149 — Max Points on a Line(C++ Java Python)
- LeetCode 70 — Climbing Stairs(C++ Java Python)
- LeetCode 141 — Linked List Cycle(C++ Java Python)
- LeetCode 26 — Remove Duplicates from Sorted Array(C++ Java Python)
- LeetCode 19 — Remove Nth Node From End of List(C++ Java Python)
- LeetCode 62 — Unique Paths(C++ Java Python)