当前位置:网站首页>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;
}
}
};
边栏推荐
猜你喜欢
MLP neural network, GRNN neural network, SVM neural network and deep learning neural network compare and identify human health and non-health data
PAT乙级 1002 写出这个数
(2022牛客多校四)A-Task Computing (排序+动态规划)
typescript24 - type inference
Risk strategy important steps of tuning method
剑指 Offer 68 - II. 二叉树的最近公共祖先
Error using ts-node
Valentine's Day Romantic 3D Photo Wall [with source code]
What is dynamic programming and what is the knapsack problem
y83.第四章 Prometheus大厂监控体系及实战 -- prometheus告警机制进阶(十四)
随机推荐
Write a method to flatten an array and deduplicate and sort it incrementally
typescript24-类型推论
PMP子过程定义总结
Advice given by experts with four years of development experience in Flutter tutorial
【愚公系列】2022年07月 Go教学课程 023-Go容器之列表
挑战52天背完小猪佩奇(第01天)
MySQL-DML语言-数据库操作语言-insert-update-delete-truncate
在沈自所的半年总结
lambda
High Numbers | 【Re-integration】Line Area Score 880 Examples
Flutter Tutorial 01 Configure the environment and run the demo program (tutorial includes source code)
This article takes you to understand the past and present of Mimir, Grafana's latest open source project
How to promote new products online?
lambda
PMP 项目质量管理
初识shell脚本
Game Theory (Depu) and Sun Tzu's Art of War (42/100)
出现Command ‘vim‘ is available in the following places,vim: command not found等解决方法
[FPGA tutorial case 43] Image case 3 - image sobel edge extraction through verilog, auxiliary verification through MATLAB
Message queue MySQL table for storing message data