当前位置:网站首页>leetcode 9. 回文数
leetcode 9. 回文数
2022-08-11 04:43:00 【_刘小雨】
作者简介:C/C++ 、Golang 领域耕耘者,创作者
个人主页:作者主页
活动地址:CSDN21天学习挑战赛
题目来源: leetcode官网
如果感觉博主的文章还不错的话,还请关注 、点赞 、收藏🧡三连支持一下博主哦~~~
题目描述
给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
例如,121 是回文,而 123 不是。
示例1:
输入:x = 121
输出:true
示例2:
输入:x = -121
输出:false
解释:从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
示例 3:
输入:x = 10
输出:false
解释:从右向左读, 为 01 。因此它不是一个回文数。
🧡 算法分析
三种方法
直接转化字符串进行比较
用的库函数,在面试中可能不推荐,库函数的原理也是一个一个字符进行逆序转化逆序数字在进行比较(推荐)
比较数字的一般字符
上一种方法的优化,不过时间复杂度没有优化
代码实现
class Solution {
public:
bool isPalindrome(int x) {
// 字符串方法
// if(x < 0) return false;
// string t = to_string(x);
// return t == string(t.rbegin(), t.rend()); // 直接初始化t 的翻转字符串
// 转化数字方法
if(x < 0) return false;
int y = x;
long long re = 0;
while(x)
{
re = re * 10 + x % 10;
x /= 10;
}
return re == y;
}
};
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0 || x && x % 10 == 0) return false;
int s = 0;
while (s <= x)
{
s = s * 10 + x % 10;
if (s == x || s == x / 10) return true; // 分别处理整数长度是奇数或者偶数的情况
x /= 10;
}
return false;
}
};
执行结果:

时间复杂度分析
其中数字遍历一次, 时间复杂度为O(n)
如果觉得对你有帮助的话:
点赞,你的认可是我创作的动力!
🧡 收藏,你的青睐是我努力的方向!
️ 评论,你的意见是我进步的财富!
边栏推荐
- 洛谷P5139 z小f的函数
- 视觉任务种常用的类别文件之一json文件
- CAD2020 打开错误报告 e06d7363h Exception at 13644F69h
- 阿里云发布3大高性能计算解决方案
- .NET Custom Middleware
- How to learn machine learning?machine learning process
- 无线电射频能量的收集
- "98 BST and Its Verification" of the 13th day of leetcode brushing series of binary tree series
- 1815. 得到新鲜甜甜圈的最多组数 状态压缩
- 走出迷宫的最短路径
猜你喜欢

对象的创建以及显示转换

Clang Code Model: Error: The clangbackend executable “X:/clangbackend.exe“ could not be started

"239 Sliding Window Maximum Value" on the 16th day of LeetCode brushing

"104 Maximum Depth of Binary Trees" in LeetCode's Day 12 Binary Tree Series

The principle, architecture, implementation, practice of "transfer" and "search", no need to be afraid of interviews

梅克尔工作室--OpenEuler培训笔记(1)

Apache初体验

Use jackson to parse json data in detail

【人话版】WEB3将至之“权益的游戏”

CAN/以太网转换器 CAN与以太网互联互通
随机推荐
「转」“搜索”的原理,架构,实现,实践,面试不用再怕了
【ImageNet】数据集1000个类的名称
力扣——旋转数组的最小数字
map and set - natural search and lookup semantics
剑指offer_抽象建模能力
[Server installation Redis] Centos7 offline installation of redis
redis按照正则批量删除key
Word2021 中的图片保存后就变模糊了
增加PRODUCT_BOOT_JARS及类 提供jar包给应用
拼多多店铺营业执照相关问题
【组成原理 九 CPU】
The principle, architecture, implementation, practice of "transfer" and "search", no need to be afraid of interviews
干货:服务器网卡组技术原理与实践
FPGA工程师面试试题集锦111~120
Selenium自动化测试框架工作原理你明白了吗?
Bubble sort and heap sort
嵌入式分享合集33
洛谷P4847 银河英雄传说V2
自研能力再获认可,腾讯云数据库入选 Forrester Translytical 报告
MySQL database storage engine and database creation, modification and deletion