leetcode 9. Palindrome Number(判断是不是回文数)

题目要求:

判断一个整数是不是回文数, 返回 true or false。

回文数的定义:在数学中 设n是一任意自然数。若将n的各位数字反向排列所得自然数n1与n相等,则称n为一回文数。例如,若n=1234321,则称n为一回文数;但若n=1234567,则n不是回文数。(来源百度百科回文数

示例:

Example 1

Input : 121
Output : true

Example 2

Input : -121
Output :false

Example 3

Input : 120
Output : 21
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

思路:

本题可以参考(leetcode 7 翻转一个整数leetcode 7)的做法,将输入的数字通过to_string()进行类型转换,然后通过库函数reverse()进行倒序操作,最后判断两个数字是否相等即可。

与第7题不同的是:

由于本题需要进行比较,所以倒序的结果要进行保存

主要代码 ( C++ ):

// leetcode 009
// palindrome number
class Solution {
public:
    bool isPalindrome(int x) {
        string s = to_string(x);
        string r = s;
        reverse(r.begin(),r.end());
        return(r==s);
    }
};

原题链接:https://leetcode.com/problems/palindrome-number/

猜你喜欢

转载自blog.csdn.net/qq_37466121/article/details/85015027
今日推荐