首页 > 其他 > 详细

Palindrome Number

时间:2016-05-13 10:10:27      阅读:200      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!