[LeetCode] Palindrome Number

1.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.

2.題目要求:驗證回文字符串。

3.方法:利用取整和取余來獲得我們想要的數(shù)字,比如 1221 這個數(shù)字,如果 計算 1221 / 1000, 則可得首位1, 如果 1221 % 10, 則可得到末尾1,進行比較,然后把中間的22取出繼續(xù)比較。

4.代碼:
class Solution {
public: bool isPalindrome(int x) {
if (x < 0)
return false;
int div = 1;
while (x / div >= 10)
div *= 10; while (x > 0) {
int left = x / div;
int right = x % 10;
if (left != right)
return false;
x = (x % div) / 10;
div /= 100;
}
return true;
}
};

?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容