題目出處
https://leetcode.com/problems/palindrome-number/
判斷一個數字是不是迴文數字, 即把數字反轉,還是自己。
要求是不能顯式申請新的內存空間。
分析:
1. 處理過程中必然會用到臨時變量, 而處理過程中必然會有一個過程, 可以考慮用遞歸。
2. 負數再有"-"號, 反轉後將不是一個數字(如-121 反轉後是 121-),所以不算是迴文。
算法如下
bool check(int a, int t){
if(a == t) return true;
if(a < t) return false;
t = t*10 + a % 10;
if(a == t) return true;
return check(a/10, t);
}
bool isPalindrome(int x) {
if(x < 0) return false;
if(x < 10)return true;
if(x % 10 == 0) return false;
return check(x, 0);
}