9. Palindrome Number
题目描述
判断一个整数是不是回文(即为正反顺序念相同的字符串)
思路
负数当然是没可能了;
正数的情况先转换成字符串,然后头尾比较
代码
javascript
/**
* @param {number} x
* @return {boolean}
*/
var isPalindrome = function(x) {
if (x < 0) return false;
if (x == 0) return true;
var str = x.toString();
var i = 0, j = str.length - 1;
var result = true;
while (j - i >= 1) {
if (str[i] != str[j]) {
result = false;
return result;
}
i++;
j--;
}
return result;
};
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0 ) return false;
if (x == 0) return true;
string s = integerToString(x);
int i = 0;
int j = s.length() - 1;
while(j - i >= 1) {
if (s[i] != s[j]) {
return false;
}
i++;
j--;
}
return true;
}
string integerToString(int n) {
ostringstream stream;
stream << n;
return stream.str();
}
};