LeetCode 9: Palindrome Number
Posted alpaca
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 9: Palindrome Number相关的知识,希望对你有一定的参考价值。
Description:
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121 Output: true
Example 2:
Input: -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:
Coud you solve it without converting the integer to a string?
描述:
确定给定数字是否是回文数字。如果某个数字顺序读和逆序读时一致,则该数字为回文数字。
例子1:
输入:121 输出:true
例子2:
输入:-121 输出:否 解释:正序读表示-121,逆序读表示121-,两者不相同
例子3:
输入:10 输出:否
方法一:转换为字符串,并判断字符串是否为回文字符串。
class Solution { public: bool isPalindrome(int x) { if(x < 0) return false; string s; while(x) { int n = x % 10; s.push_back(n + ‘0‘); x = x / 10; } int i = 0, j = s.length() - 1; while(i < j) { if(s[i] != s[j]) return false; i++; j--; } return true; } };
时间复杂度为O(max(lg(x), n),空间复杂度为O(lg(x))。
方法二: 折半反转。
以上是关于LeetCode 9: Palindrome Number的主要内容,如果未能解决你的问题,请参考以下文章