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

Palindrome Number

时间:2016-05-13 10:10:34      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

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

click to show spoilers.

Some hints:

Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

注意: negetive integers are not palindromes

思路: 将数字reverse 如果 reverse之后等于原数字则为palindrome 在reverse的过程中注意overflow的情况。

 1 public class Solution {
 2     public boolean isPalindrome(int x) {
 3         if (x < 0) {
 4             return false;
 5         }
 6         return x == reverse(x);
 7     }
 8     
 9     int reverse(int n) {
10         int result = 0;
11         while (n != 0) {
12             int temp = result * 10 + n % 10;
13             if (temp / 10 != result) {
14                 result = 0;
15                 break;
16             }
17             n = n / 10;
18             result = temp;
19         }
20         return result;
21     }
22     
23 }

 

Palindrome Number

标签:

原文地址:http://www.cnblogs.com/FLAGyuri/p/5486358.html

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