LeetCode 9. Palindrome Number (回文数字)

Determine whether an integer is a palindrome. Do this without extra space.

 


题目标签:Math

  题目给了我们一个int x, 让我们判断它是不是回文数字。

  首先,负数就不是回文数字,因为有个负号。

  剩下的都是正数,只要把数字 reverse 一下,和原来的比较,一样就是回文。

  当有overflow 的时候,返回一个负数就可以了(因为负数肯定不会和正数相等)。

  

 

Java Solution:

Runtime beats 61.47% 

完成日期:06/12/2017

关键词:Palindrome

关键点:reverse number

 1 class Solution 
 2 {
 3     public boolean isPalindrome(int x) 
 4     {
 5         if(x < 0)
 6             return false;
 7         
 8         int pd = reverse(x);
 9         
10         return x == pd ? true : false;
11     }
12     
13     public int reverse(int num)
14     {
15         int res = 0;
16         
17         while(num != 0)
18         {
19             int tail = num % 10;
20             int newRes = res * 10 + tail;
21             
22             if((newRes - tail) / 10 != res) // check overflow
23                 return -1; // -1 will not equal to positive number
24             
25             res = newRes;
26             num = num / 10;
27         }
28         
29         return res;
30     }
31 }

参考资料:N/A

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

posted @ 2017-12-12 08:40  Jimmy_Cheng  阅读(209)  评论(0编辑  收藏  举报