9. 回文数
给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
例如,121 是回文,而 123 不是。
当原始数字小于或等于反转后的数字时,就意味着我们已经处理了一半位数的数字了。这时候只要return (翻转后的数字==原始数的一半)
class Solution { public bool isPalindrome(int x) { if (x < 0 || (x % 10 == 0 && x != 0)) { return false; }
int revertedNumber = 0; while (x > revertedNumber) { revertedNumber = revertedNumber * 10 + x % 10; x /= 10; } // 奇数时,通过revertedNumber/10去除处于中位的数字,不用去判断 return x == revertedNumber || x == revertedNumber / 10; } };