LeetCode算法题——Palindrome Number

来源:互联网 发布:js获取单选框是否选中 编辑:程序博客网 时间:2024/05/31 05:27

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

click to show spoilers.

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.

算法思想:
1 将整数转换成倒序的整数,然后比较两个数是否相等
2 提取头尾两个数,然后判断它们是否相等,判断后去掉头尾两个数

#include <iostream>
using namespace std;
class Solution {
public:
    bool isPalindrome(int x) {
        int y=x;
        if(y<0){
            return false;
        }
        int maxNum[10]={2,1,4,7,4,8,3,6,4,7};
        bool flag=false;
//        bool isNeg=false;
//        if(y<0){
//            y=-y;
//            isNeg=true;
//        }
        if(y/1000000000!=0){
            flag=true;
        }

        int s=0,j=0,m;
        while(y!=0){           
            m=y%10;
            if(flag){
                if(m>maxNum[j]){
                    return false;
                }else if(m<maxNum[j]){
                    flag=false;
                }
                j++;
            }
            y=y/10;
            s=s*10+m;
        }
//        if(isNeg){
//            s=-s;
//        }
        if(s==x){
            return true;
        }else{
            return false;
        }
//        return s;
    }
};

int main(){
    Solution sol;
    cout<<sol.isPalindrome(-2147447412)<<endl;
}
0 0