码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]9. Palindrome Number回文数

时间:2018-12-28 16:40:20      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:leetcode   没有   from   isp   tag   eth   xpl   without   rom   

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

Input: 121
Output: true

Example 2:

Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Follow up:

Coud you solve it without converting the integer to a string?

 

还是回文的问题,这题没有给出数字的区间,不过我们不用担心,回文数正反一样所以反过来也不会溢出的,我们可以利用之前的整数翻转的方法,如果回文reverse之后肯定相等

另外根据题意负数肯定是不回文的

class Solution {
    public boolean isPalindrome(int x) {
        if(x<0) return false;
        if(x!=reverse(x)) return false;
        return true;
    }
    
    public int reverse(int x) {
        int res = 0,tag=0;
        while (x != 0) {
            tag = res * 10 + x % 10;
            if (tag / 10 != res) return 0;
            res = tag;
            x = x / 10;
        }
        return res;
    }
}

 

[LeetCode]9. Palindrome Number回文数

标签:leetcode   没有   from   isp   tag   eth   xpl   without   rom   

原文地址:https://www.cnblogs.com/jchen104/p/10191192.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!