前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode题组:第9题-回文数

LeetCode题组:第9题-回文数

作者头像
K同学啊
发布2020-04-08 15:57:26
3200
发布2020-04-08 15:57:26
举报

1.题目:回文数 判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。

示例 1:

输入: 121 输出: true

示例 2:

输入: -121 输出: false 解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。

示例 3:

输入: 10 输出: false 解释: 从右向左读, 为 01 。因此它不是一个回文数。


2.我的解答:

代码语言:javascript
复制
#include <stdio.h>

//函数申明
bool isPalindrome(int x); 

bool isPalindrome(int x){
	if(x<0) return false;
	
	long y=0;
	int temp=x;
	
	while(temp){
		y = y*10 + temp%10;
		temp = temp/10;
	}
	if(x==y) return true;
	else return false;
}

int main()
{
   int x=12321;
   printf("%d\n",isPalindrome(x));
   return 0;
}

3.题目进阶 将整数转为字符串来解决这个问题

4.进阶版解答

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>

//函数申明
bool isPalindrome(int x); 

bool isPalindrome(int x){
	if(x<0) return false;
	//临时复制x的值 
	int temp = x;
	int length = 0,flag1,flag2;
	//计量x的长度 
	while(temp){
		temp = temp/10;
		length++;
	}
	
	char *X;
	itoa(x,X,length);
	
	//从字符串头与尾部同时遍历 
	flag2 = length-1;
	while(flag1<flag2){
		if(X[flag2] != X[flag1]) return false;
	}
	return true;

}

int main()
{
   int x=-12321;
   printf("%d\n",isPalindrome(x));
   return 0;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-04-05 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档