I don't know what the future ho|

Sheldon2

园龄:3年3个月粉丝:2关注:4

LeetCode[9. 回文数]

回文数
[题目来源leetcode]https://leetcode.cn/problems/palindrome-number/
给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
例如,121 是回文,而 123 不是。

示例 1:
输入:x = 121
输出:true
示例 2:
输入:x = -121
输出:false

解释:从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。

示例 3:
输入:x = 10
输出:false

解释:从右向左读, 为 01 。因此它不是一个回文数。

提示:

231<=x<=2311

解法一
class Solution {
public:
bool isPalindrome(int x) {
string s = to_string(x);
string ns = s;
reverse(s.begin(),s.end());
return s == ns;
}
};
解法二
class Solution {
public:
//反转数字
long solve(int m)
{
long ans = 0;
while(m)
{
int temp = m % 10;
ans = ans * 10 + temp;
m /= 10;
}
return ans;
}
bool isPalindrome(int x) {
if(x < 0) return false;
if(x % 10 == 0 && x != 0) return false;
//12345
int ans = solve(x);
return ans == x;
}
};

本文作者:Shedlon2

本文链接:https://www.cnblogs.com/Sheldon2/p/16721313.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Sheldon2  阅读(16)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起