#include<string> usingnamespace std; classSolution { public: boolisPalindrome(int x){ // 0-9是回文数而小于0的肯定不是回文数 if (x < 0 || (x >= 0 && x < 10)) { return x >= 0; } // 先将x转换为字符串 string str = to_string(x); int left = 0, right = str.length() - 1; while (left < right) { if (str[left] != str[right]) { returnfalse; } left++; right--; } returntrue; } };
这种解法要比上一种解法快不少,因为经过的判断不是很多
进阶解法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include<string> usingnamespace std; classSolution { public: boolisPalindrome(int x){ if (x < 0 || (x % 10 == 0 && x != 0)) { returnfalse; } int y = 0; while (x > y) { y = y * 10 + x % 10; x = x / 10; } if (x == y || x == y / 10) { returntrue; } else { returnfalse; } } };