9. 回文数 Palindrome Number
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Follow up: Could you solve it without converting the integer to a string?
Input: x = 121
Output: true
可以只反转一半,如果数字前半部分和后半部分相等,则为回文。
对于长度为奇数的数字,舍弃中间位,例如 12321, 分成12 和123, 123直接舍掉3即可。
public boolean isPalindrome(int x) { if(x < 0 || x % 10 == 0 && x != 0) return false; int half_end = 0; while(x > half_end){ half_end = half_end * 10 + x % 10; x = x /10; } if( x == half_end || x == half_end / 10 ) return true; return false; }
参考链接:
https://leetcode.com/problems/palindrome-number/
https://leetcode-cn.com/problems/palindrome-number/