9. Palindrome Number

来源:互联网 发布:成都培训java多少人 编辑:程序博客网 时间:2024/06/05 03:30

9. Palindrome Number

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

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.
Analysis:
回文体。
这里用了两种方法:
1. 将数字反转,然后做比对是否相等
2. 不断地取第一位和最后一位(10进制下)进行比较
Source Code(C++):

#include <iostream>#include <vector>#include <algorithm>using namespace std;/*******************法一:不断地取第一位和最后一位(10进制下)进行比较,相等则取第二位和倒数第二位,直到完成比较或者中途找到了不一致的位*****************************//*class Solution {public:    bool isPalindrome(int x) {        if (x<0){            return false;        }        else {            int div = 1;            while(x/div > 9) {                div *= 10;            }            while(x > 0) {                int l = x/div;                int r = x%10;                if (l != r) {                    return false;                }                x = x%div/10;                div /= 100;            }            return true;        }    }};*//*******************法二:将数字反转,对比是否相等*****************************/class Solution {public:    bool isPalindrome(int x) {        if (x<0){            return false;        }        else if (x==0) {            return true;        }        else {            int x_copy=x;            int x_reverse=0;            int x_tail=0;            while(x) {                x_tail=x%10;                x /= 10;                x_reverse = x_reverse*10+x_tail;            }            if (x_copy == x_reverse) {                return true;            }            else {                return false;            }        }    }};int main() {    Solution sol;    cout << sol.isPalindrome(0);    return 0;}
0 0
原创粉丝点击