LeetCode_Palindrome Number

来源:互联网 发布:身份证号码找人软件 编辑:程序博客网 时间:2024/06/07 17:51

Palindrome Number

 

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

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.


题目要求输入一个整形数字,判断该数字是否为回文数(在该题中,负数不是回文数),提示中说有多重实现方法,在此使用两种方法:

java解题

第一种:借助String,首尾字符依次判断是否相等:

public static boolean isPalindrome(int x) {if(x<0)return false;String s = x+"";for(int i=0,j=s.length()-1;i<j;i++,j--){if(s.charAt(i)!=s.charAt(j))return false;}return true;}

第二种:纯粹靠计算,将一个int型数字最低位到最高位依次翻转成为一个新的整数,判断前后两个数是否相等,需要注意的是,翻转过后的数字可能超过int的范围,需要特别考虑:

public static boolean isPalindrome(int x) {if(x<0)return false;long y=(long)x;long result = 0;          while (x != 0) {              result = result * 10 + x % 10; // 每一次都在原来结果的基础上变大10倍,再加上余数              x = x / 10; // 对x不停除10          }        if(y==result)        return true;return false;}


0 0