https://leetcode.com/problems/palindrome-number/
这一题可以将数字直接反转,如果反转后数字和原数字相同,则一定是回文数。当然对于负数可以直接返回false
具体代码如下:
class Solution { public: bool isPalindrome(int x) { if (x < 0) { return false; } int temp = x; int64_t reverse = 0; while (temp != 0) { reverse = reverse * 10 + temp % 10; temp /= 10; } return reverse == x ? true : false; } };
但是这种算法不够优化,可以只反转后半部分,之后与前一半进行对比即可。
具体代码如下:
class Solution { public: bool isPalindrome(int x) { if (x < 0 || (x != 0 && x % 10 == 0)) { return false; } int reverseHalf = 0;//将x的后一半进行反转,并存储在reverseHalf中 while (reverseHalf < x) {//x只留下前一半(如果x为奇数,中间那一位给后一半) reverseHalf = reverseHalf * 10 + x % 10; x /= 10; } return reverseHalf == x || reverseHalf / 10 == x; } };
参考:https://leetcode.com/problems/palindrome-number/discuss/5165/An-easy-c%2B%2B-8-lines-code-(only-reversing-till-half-and-then-compare)