当前位置:网站首页>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;
}
}
};
边栏推荐
猜你喜欢

typescript28 - value of enumeration type and data enumeration

基于Arduino制作非接触式测温仪

leetcode:126. Word Solitaire II

状态压缩dp

开源许可证 GPL、BSD、MIT、Mozilla、Apache和LGPL的区别

How to promote new products online?

typescript25 - type assertion

Pyspark Machine Learning: Vectors and Common Operations

Excel record of integer programming optimization model to solve the problem

Mysql基础篇(Mysql数据类型)
随机推荐
What is dynamic programming and what is the knapsack problem
Dynamic Programming 01 Backpack
EntityFramework saves to SQLServer decimal precision is lost
Difference Between Compiled and Interpreted Languages
MLP neural network, GRNN neural network, SVM neural network and deep learning neural network compare and identify human health and non-health data
Pyspark机器学习:向量及其常用操作
【目标检测】YOLOv7理论简介+实践测试
typescript23-tuple
智芯传感输液泵压力传感器 为精准智能控制注入科技“强心剂”
Message queue design based on mysql
lambda
Optional parameters typescript19 - object
怀念故乡的面条
报错:AttributeError: module ‘matplotlib’ has no attribute ‘figure’
罗技鼠标体验记录
Typescript22 - interface inheritance
剑指 Offer 68 - II. 二叉树的最近公共祖先
2022-07-31: Given a graph with n points and m directed edges, you can use magic to turn directed edges into undirected edges, such as directed edges from A to B, with a weight of 7.After casting the m
【愚公系列】2022年07月 .NET架构班 085-微服务专题 Abp vNext微服务网关
6-23漏洞利用-postgresql代码执行利用