判断回文数字

题目出处

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);
    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章