[題目] 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.
[中文翻譯] 確定整數(shù)是否是回文。 不使用額外的空間。 提示: 負(fù)整數(shù)是回文嗎? (如,-1) 如果你正在考慮將整數(shù)轉(zhuǎn)換為字符串,請(qǐng)注意不使用額外空間的限制。 您也可以嘗試反轉(zhuǎn)整數(shù)。 但是,如果已解決了“Reverse Integer”的問(wèn)題,則知道反向整數(shù)可能溢出。 你將如何處理這種情況? 有一個(gè)更通用的方法來(lái)解決這個(gè)問(wèn)題。
[解題思路] 先反轉(zhuǎn)整數(shù),然后比較反轉(zhuǎn)的整數(shù)是否與原整數(shù)相同。對(duì)于溢出的情況,使用long long即可解決。不是很確定,這種方法是否違反了不適用額外空間的限制。
看Discuss的時(shí)候,發(fā)現(xiàn)其實(shí)整數(shù)只需要反轉(zhuǎn)一半即可。
[C++代碼]
class Solution {public: bool isPalindrome(int x) { if (x < 0) return false; long long y = 0; int tmp = x; while (x > 0) { y = y * 10 + x % 10; x = x / 10; } return tmp == y; }};新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注