9. Palindrome Number题目和答案详解

来源:互联网 发布:淘宝章鱼哥代购靠谱吗 编辑:程序博客网 时间:2024/05/17 21:58

1 题目简述

Determine whether an integer is a palindrome. Do this withoutextra space.

判断一个整数是否为回文。这样做没有多余的空间。

 

Could negative integers be palindromes? (ie, -1)

负数是否是回文数?(ie,-1)

 

If you are thinking of converting the integer tostring, note the restriction of using extra space.

如果您正在考虑将整数转换为字符串,请注意使用额外空间的限制。

 

You could also try reversing an integer. However, ifyou have solved the problem "Reverse Integer", you know that thereversed integer might overflow. How would you handle such case?

您还可以尝试反转整数。但是,如果您已经解决了“反向整数”这个问题,那么您知道反向整数可能会溢出。你将如何处理这种情况?

2 答案详解

(1) 规则分析

  简而言之,回文整型数的规则有几点:

  1)负数不是回文;

  2)剩下的整数中,0~9是回文;

  3)此外,形似12321和456654的整型数也是回文。

(2) 解决思想

  本次解答采用C++编写,C++相对于C语言的一个重要的特点是:面向对象编程(OOP),故我们采用类的方法来实现所述要求。

  首先,按照回文整型数的前两点规则,先判断一个整型数是否为回文;

  然后,对于剩下的两位数以上(>=10)的整型数,先求取其位数;

  最后,从整型数的最高位和最低位开始,往数的中间遍历,若遇到不同的数字则判定为非回文,否则继续遍历,直到遍历到数的中间位置为止。

  为了更好地理解这一点,举个例子:假设有一个整型数number=1234221,它的位数为:7。故可以找到求取最高位和最低位数字的方法,最高位数字1为:number/(10^6)%10,最低位数字1为:number/(10^1)%(10^0);类似的,第二高位数字2为:number/(10^5)%10,第二低位数字2为:number/(10^2)%(10^1);以此类推,可以找到求取的数字与位数的关系。由此可见,共需要执行7/2=3次。

(3) 设计程序

  所设计的程序采用类模板,这样可以对代码进行重用,从而对各种整数进行反转时无需做过多的程序改动,程序如下:
#include <iostream>#include <cmath>using std::cout;using std::endl;template<class T>class Palindrome_Number{private:    T num_;public:    Palindrome_Number(const T& num = 0):num_(num) {}    bool is_palindrome();private:    T pow_(T num,const int& time) {        return pow(num,time);    }};template<class T>bool Palindrome_Number<T>::is_palindrome(){    int count(0);    T num(num_);    int divisor(10);    if(num_ < 0) {        return false;    } else if(num_ >= 0 and num_ < 10) {        return true;    }    while(num = num/divisor) {        count++;    }    count++;    T& time(num);    time = 1;    do {        if( num_%pow_(divisor,time)/pow_(divisor,time-1) != num_/pow_(divisor,count-time)%divisor ) {            return false;        }        time++;    } while(time != count/2 + 1);    return true;}int main(){    int int_num = 123454321;    Palindrome_Number<int> pn(int_num);    cout << "Integer number:" << int_num << endl;    if(pn.is_palindrome()) {        cout << "It is palindrome." << endl;    } else {        cout << "It is not palindrome." << endl;    }}
程序运行结果为:

Integer number:12345321

It is palindrome.

原创粉丝点击