当前位置:网站首页>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;
}
}
};
边栏推荐
- Invalid classes inferred from unique values of `y`. Expected: [0 1 2], got [1 2 3]
- 数据比对功能调研总结
- Article summary: the basic model of VPN and business types
- Pyspark Machine Learning: Vectors and Common Operations
- 开源许可证 GPL、BSD、MIT、Mozilla、Apache和LGPL的区别
- Difference Between Compiled and Interpreted Languages
- leetcode:126. Word Solitaire II
- MySQL-数据操作-分组查询-连接查询-子查询-分页查询-联合查询
- 怀念故乡的月亮
- 认真对待每一个时刻
猜你喜欢
随机推荐
ModuleNotFoundError: No module named ‘tensorflow.keras‘报错信息的解决方法
【愚公系列】2022年07月 Go教学课程 025-递归函数
Lawyer Interpretation | Guns or Roses?Talking about Metaverse Interoperability from the Battle of Big Manufacturers
Mysql中的数据类型和运算符
万字逐行解析与实现Transformer,并进行德译英实战(三)
【愚公系列】2022年07月 .NET架构班 085-微服务专题 Abp vNext微服务网关
MySQL-DML语言-数据库操作语言-insert-update-delete-truncate
Game Theory (Depu) and Sun Tzu's Art of War (42/100)
Valentine's Day Romantic 3D Photo Wall [with source code]
PMP 项目质量管理
PMP 80个输入输出总结
25. 这三道常见的面试题,你有被问过吗?
7月编程排行榜来啦!这次有何新变化?
初识shell脚本
Pyspark机器学习:向量及其常用操作
typescript21 - Comparison of Interfaces and Type Aliases
Step by step hand tearing carousel Figure 3 (nanny level tutorial)
typescript23-tuple
动态规划 01背包
/etc/fstab









