标签:个数 eth -- 正序 文字 判断 length ring amp
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))。
方法二: 折半反转。
标签:个数 eth -- 正序 文字 判断 length ring amp
原文地址:https://www.cnblogs.com/alpaca/p/9488612.html