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.
判斷一個整數是否為回文數。不要利用額外的空間。
一些提示:負數不是回文數;如果考慮將整數轉化為字符串,注意空間的限制;如果嘗試轉置這個整數,要注意溢出的問題。
這裡利用題目《
public class Solution { private int i; private int labelnum; private long finalnum; private int finalnnum; private int checkresult; private int label; private int y; private boolean blabel; public boolean isPalindrome(int x) { y=reverse(x);//將原整數進行轉置 if (y==0) { if(x==y) blabel=true;//轉制前後都是0 else blabel=false;//原整數不是0,轉置後變為0,表明出現溢出 } else if(x<0)//負數不是回文數 blabel=false; else if(x==y) blabel=true; else blabel=false; return blabel; } public int reverse(int x) { String s1=Integer.toString(x); if(s1.charAt(0)=='-') { String s2=-; String finals2=-; String Judges2=; long num1=0L; for(i=s1.length()-1;i>=1;i--) s2+=s1.charAt(i); for(i=1;i=0;i--) s2+=s1.charAt(i); for(i=0;i = '0') { int currentDigit = digit - '0'; /* * 異常情況4:已經等於Integer.MAX_VALUE / 10,判斷要添加的最後一位的情況: * 如果是負數的話,最後一位最大是8 如果是正數的話最後一位最大是7 * Int 范圍:四個字節,-2147483648~2147483647 */ if (result == Integer.MAX_VALUE / 10) { if ((negative == false && currentDigit > 7) || (negative && currentDigit > 8)) { checkresult=0; } /* * 異常情況5:已經大於Integer.MAX_VALUE / 10 * 無論最後一位是什麼都會超過Integer.MAX_VALUE */ } else if (result > Integer.MAX_VALUE / 10) { checkresult=0; } int next = result * 10 + currentDigit; result = next; } } return checkresult; } }
public class Solution { public boolean isPalindrome(int x) { if(x<0) return false;//負數不是回文 if(x==0) return true; //對數值進行翻轉,回文翻轉之後還等於原來的數 int reverseNum=0; int num=x; while(num>0) { int modnum=num%10; //考慮翻轉會溢出的情況 if((reverseNum>Integer.MAX_VALUE/10)||((reverseNum==Integer.MAX_VALUE/10)&&(modnum>Integer.MAX_VALUE%10))) return false; reverseNum=reverseNum*10+modnum; num=num/10; } if(reverseNum==x) return true; else return false; } }