跳转至

9.回文数

//根据第7题可以将数字翻转,翻转后如果等于原来的数字则是回文数。
class Solution {
    public boolean isPalindrome(int x) {
        if(x < 0){
            return false;
        }
        int rev = 0;
        int y = x;
        while(x!=0){
            rev = 10*rev + x%10;
            x /= 10;
        }
        return rev == y;
    }
}
//根据回文数的特点,只需要翻转一半与另一半进行对比,就可以判断是否是回文数字。
public class Solution {
    public bool IsPalindrome(int x) {
        // Special cases:
        // As discussed above, when x < 0, x is not a palindrome.
        // Also if the last digit of the number is 0, in order to be a palindrome,
        // the first digit of the number also needs to be 0.
        // Only 0 satisfy this property.
        if(x < 0 || (x % 10 == 0 && x != 0)) {
            return false;
        }

        int revertedNumber = 0;
        while(x > revertedNumber) {
            revertedNumber = revertedNumber * 10 + x % 10;
            x /= 10;
        }
        return x == revertedNumber || x == revertedNumber/10;
    }
}