9_Palindrome Number
9.Palindrome Number
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.Follow up: Coud you solve it without converting the integer to a string?
版本一: 思想是把数字拆成一位一位的数组, 首位比较, 好像转换成字符串了, 违反Follow up了
// 偶数位时回文数的退出是关键, 
class Solution {
public:
    bool isPalindrome(int x) {
        bool ret = false;
        vector<int> position;
        int begin = 0, end = 0;
        
        if (x < 0 ) {
            return ret;
        }
        else if (0 == x) {
            return true;
        }
        else {
            while (0 != x) {
                position.push_back(x % 10);
                x /= 10;
            }
            end = position.size() - 1;
            while (begin != end) {
                if (position[begin] != position[end]) {
                    return ret;
                }
                // 偶数个位数时终止循环, 否则判断之后数组访问越界, 位置不能换
                if ((begin + 1) == end) {
                    break;
                }
                begin++;
                end--;
            }
            ret = true;
            return ret;
        }
    }
};
版本二: 借助7_Reverse Integer翻转数字的思想, 比较原数字和翻转之后的数字是否相同进行判断
// 借助[7_Reverse Integer](https://www.cnblogs.com/hesper/p/10397725.html)翻转数字的思想
// 比较原数字和翻转之后的数字是否相同进行判断
class Solution {
public:
    bool isPalindrome(int x) {
        int y = x;
        //int tmp = 0;  // int 类型x翻转 后数字范围可能大于int最大值
        long tmp = 0;
        vector<int> position;
        int begin = 0, end = 0;
        
        if (x < 0 ) {
            return false;
        }
        else {
            while (0 != x) {
                tmp = tmp*10 + x%10;
                x /= 10;
            }
            
            if (tmp == y) {
                return true;
            }
            else {
                return false;
            }
        }
    }
};
LeetCode精简版
class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0)
          return false;
        long long result = 0;
        int temp = x;
        while(temp) {
          result *= 10;
          result += temp % 10;
          temp /= 10;
        }
        if ((int)result == x)
          return true;
        return false;
    }
};
                    
                
                
            
        
浙公网安备 33010602011771号