Title :

Determine whether an integer is a palindrome. Do this without extra space.

 

思路1 : 将数字翻转,然后看是否相等。是否越界的问题,如果真是回文串是不会越界的

class Solution {
public:
    int reverseInteger(int x){
        int result = 0;
        while (x){
            result = result * 10 + x % 10;
            x /= 10;
        }
        return result;
    }
    bool isPalindrome(int x) {
        if (x < 0)
            return false;
        int reverse = reverseInteger(x);
    //    cout<<reverse<< " "<<x<<endl;
        return (reverse == x);
    }
};

思路2:

从左右两边分别验证是否相等

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0)
            return false;
            
        if (x < 10)
            return true;
            
        int digits = 0;
        int t = x;
        int d = 0;
        while(t != 0) t /= 10, ++d;
        
        int left = pow(10, d - 1);
        int right = 1;
        while( left >= right)
        {
            if (x / left % 10 != x / right % 10)
                return false;
            
            left /= 10;
            right *= 10;
        }
        return true;
    }
};

 

相关文章:

  • 2022-02-20
  • 2021-08-14
  • 2022-01-20
  • 2021-06-12
  • 2022-12-23
猜你喜欢
  • 2022-03-01
  • 2021-12-05
  • 2022-02-08
  • 2022-01-08
  • 2022-01-09
相关资源
相似解决方案