LeetCode C++ 9. Palindrome Number 简单
发布日期:2021-07-01 02:47:47 浏览次数:2 分类:技术文章

本文共 1107 字,大约阅读时间需要 3 分钟。

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

Input: 121Output: true

Example 2:

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

Example 3:

Input: 10Output: falseExplanation: Reads 01 from right to left. Therefore it is not a palindrome.

Follow up:

Coud you solve it without converting the integer to a string?

题意:判断一个整型数据是否是一个回文数。

思路1:可以转换为字符串,然后 reverse 和原串对比。代码:

class Solution {
public: bool isPalindrome(int x) {
string s = to_string(x), t = s; reverse(t.begin(), t.end()); return s == t ? true : false; }};

思路2:将原数值转为新的回文数值,然后对比。注意,转换过程中可能出现溢出,因此使用 long long 。另外,负数一定不是回文数。代码:

class Solution {
public: bool isPalindrome(int x) {
if (x < 0) return false; else {
long long rev = 0, t = x; while (t) {
rev = rev * 10 + t % 10; t /= 10; } return x == rev ? true : false; } }};

转载地址:https://memcpy0.blog.csdn.net/article/details/106654724 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:洛谷 P1551 亲戚【并查集】
下一篇:POJ 2524 Ubiquitous Religions【并查集】

发表评论

最新留言

表示我来过!
[***.240.166.169]2024年04月10日 03时05分13秒