leetCode--回文数
2019-05-07 17:09
666 查看
题目:
我的答案(c++):
class Solution { public: bool isPalindrome(int x) { vector<int> num; int a = x; if (x < 0) return false; while (a!=0) { num.push_back(a%10); a /= 10; } int j = num.size(); for (int i=0;i<j;i++) { j = j - 1; if (num[i] != num[j]) return false; } return true; } };
结果:
官方答案:
class Solution { public: bool isPalindrome(int x) { if(x < 0 || (x % 10 == 0 && x != 0)) { return false; } int revertedNumber = 0; while(x > revertedNumber) { revertedNumber = revertedNumber * 10 + x % 10; x /= 10; } return (x == revertedNumber || x == revertedNumber/10); } };
结果:
其他人答案:
class Solution { public: bool isPalindrome(int x) { //负数一定不是回文数 if (x < 0) return false; //123321 //将这个数的后面一半拿下来,组成一个新的整数 //统计整数的的位数数 int tmp = x; int count = 0; int nnum = 0; while (tmp) { count++; tmp /= 10; } //取后面一半的位数 组成新整数 for (int i = 0; i < count / 2; i++) { //只有第一次拿下来是个 一位数,其余每次拿下来都要在上一次的nnum基础上*10 if (i == 0) { nnum = x % 10; x /= 10; } else { nnum = (x % 10) + nnum * 10; x /= 10; } } //比较新的整数 和 剩余部分整数 大小 if (count % 2 == 0) { //说明整数是偶数位,取count/2位数组成新的整数 if (x == nnum) return true; return false; } else { //整数是奇数位,取count/2位数 组成新的整数后,还需要将剩余整数再去掉最后一位 x /= 10; if (x == nnum) return true; return false; } } };
结果:
相关文章推荐
- (LeetCode)Valid Palindrome --- 判断回文字符串
- leetcode回文子串拆分-最小拆分次数
- Leetcode|Longest Palindromic Substring(最长回文的几种方法)(Manacher算法)
- 【精】leetcode - 647. Palindromic Substrings【动态规划 + 回文 + 对称性】
- 最长回文:LeetCode:5. Longest Palindromic Substring
- LeetCode——Valid Palindrome (回文判断)
- LEETCODE-9 回文数
- Palindrome Partitioning 分割字符串为回文@LeetCode
- 【LeetCode】 #9:回文数 C语言
- Leetcode题解1:最长回文子串 JAVA
- leetcode 5. Longest Palindromic Substring 最长回文子串的查找 + 按照length做DP
- LeetCode5. Longest Palindromic Substring(最长回文子串:Manacher算法)
- LeetCode 第九题 回文数/Palindrome Number
- LeetCode 9. Palindrome Number (回文数字)
- leetcode:最长回文子串
- Leetcode 5最长回文子串 Java
- leetcode——Palindrome Number 判断整数数字是否为回文(AC)
- LeetCode Palindrome Linked List (回文链表)
- LeetCode9. 回文数字
- LeetCode 5. Longest Palindromic Substring(最长回文子串)