当前位置:网站首页>LeetCode 9. 回文数
LeetCode 9. 回文数
2022-08-01 04:49:00 【PUdd】
LeetCode 9. 回文数
我的思路
映入脑海的第一个想法是将数字转换为字符串,并按字符串的长度分为奇数和偶数两种情况检查字符串是否为回文。但是,这需要额外的非常量空间来创建问题描述中所不允许的字符串。
C++代码
class Solution {
public:
bool isPalindrome(int x)
{
string s = to_string(x);
if(s.length()%2 !=0)
{
for(int i=0;i<(s.length()-1)/2;i++)//
{
if (s[i]!=s[s.length()-1-i])//
{
return 0;
}
}
return 1;
}
else
{
for(int i=0;i<s.length()/2;i++)
{
if (s[i]!=s[s.length()-1-i])
{
return 0;
}
}
return 1;
}
return 0;
}
};
翻转一半数字的解法(效率高)
class Solution {
public:
bool isPalindrome(int x)
{
// 负数 -> false; 0 -> true; 正数 -> 翻转一半; 末尾 0 -> false
if(x < 0 || (x % 10 == 0 && x !=0 )) return false;
else if(x == 0) return true;
else
{
int revert = 0;
while (revert < x)
{
revert = revert*10 + x%10;
x /= 10;
}
if(revert == x || revert/10 == x) return true;
else return false;
}
}
};
边栏推荐
- UE4 模型OnClick事件不生效的两种原因
- The Principle Of Percona Toolkit Nibble Algorithm
- MySQL-数据定义语言-DDLdatebase define language
- Valentine's Day Romantic 3D Photo Wall [with source code]
- UE4 从鼠标位置射出射线检测
- 【无标题】
- Pyspark Machine Learning: Vectors and Common Operations
- UE4 制作遇到的问题
- ICML2022 | Deep Dive into Permutation-Sensitive Graph Neural Networks
- 7 行代码搞崩溃 B 站,原因令人唏嘘!
猜你喜欢
随机推荐
开源许可证 GPL、BSD、MIT、Mozilla、Apache和LGPL的区别
What is dynamic programming and what is the knapsack problem
初识shell脚本
MLP neural network, GRNN neural network, SVM neural network and deep learning neural network compare and identify human health and non-health data
数组问题之《两数之和》以及《三数之和 》
safari浏览器怎么导入书签
Flutter Tutorial 01 Configure the environment and run the demo program (tutorial includes source code)
基于Arduino制作非接触式测温仪
The Principle Of Percona Toolkit Nibble Algorithm
The Flow Of Percona Toolkit pt-table-checksum
Mysql基础篇(Mysql数据类型)
【堆】小红的数组
Optional parameters typescript19 - object
数据比对功能调研总结
MySQL-DML语言-数据库操作语言-insert-update-delete-truncate
Visual Studio提供的 Command Prompt 到底有啥用
Message queue MySQL table for storing message data
怀念故乡的月亮
Difference Between Compiled and Interpreted Languages
基于ProXmoX VE的虚拟化家庭服务器(篇一)—ProXmoX VE 安装及基础配置









