Chinaunix首页 | 论坛 | 博客
  • 博客访问: 80814
  • 博文数量: 29
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 225
  • 用 户 组: 普通用户
  • 注册时间: 2014-03-06 15:31
文章分类

全部博文(29)

文章存档

2015年(18)

2014年(11)

我的朋友

分类: Java

2015-01-21 10:20:21

题目:Determine whether an integer is a palindrome. Do this without extra space.
题目给出的hint:

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.
解决思路:题目要求不能使用额外的空间,那么转换成string然后按照判断字符串的方法来判断是否为回文数应该是不可行的,应此解决方法如下:

点击(此处)折叠或打开

  1. public class Solution {
  2.     public boolean isPalindrome(int x) {
  3.         if(x < 0){
  4.             return false;
  5.         }
  6.         if(x < 10){
  7.             return true;
  8.         }
  9.         int sum = 0;
  10.         int reserve = x;
  11.         while(x > 0){
  12.             sum = sum*10 + x%10;
  13.             x = x/10;
  14.         }
  15.         if(sum == reserve){
  16.             return true;
  17.         }else{
  18.             return false;
  19.         }
  20.         
  21.     }
  22. }

                                                                                                                                                                                                

阅读(966) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~