博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode—— Palindrome Number
阅读量:2338 次
发布时间:2019-05-10

本文共 2514 字,大约阅读时间需要 8 分钟。

题目描述

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

判定一个整型的数字是否是回文。一个回文的正数正反读过来都是相同的

Example 1:

Input: 121

Output: true
Example 2:

Input: -121

Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:

Input: 10

Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Follow up:

Coud you solve it without converting the integer to a string?
跟进:试着解决这个问题,而不将整型数据转成字符串。

知识补充

  • sprintf(字符串指针,“数据类型”,对应数据类型的变量)
int iValue;//整型数baichar sz[10];//字符串sprintf(sz, "%d", iValue);//这句需要头文件du#include 
功用:将要输出的东西按照相应的格式存放到第一个参数的字符串中。
  • itoa(整型数,字符串首地址指针,字符串的长度)16进制数字构成的字符串
itoa(iValue, sz, 10); //这句需要头文件#include 
功用:直接将整型数转化成字符串,会自动将数字转成16进制,然后将16进制的整型数字变成字符串

问题思考

  • 方法一:转成字符串,用头指针和尾指针,从两边分别向中间进行比对
  • 方法二:将原来的数字反转并保存到新的数字中,直接比较两个数是否相同

我的代码

  • 方法一:
#include 
#include
typedef enum {
false,true} bool;bool isPalindrome(int x);int main(){
//今日份的了leetcode——palindrome number 回数 int test = 11; int res = isPalindrome(test); printf("%d \n",res); return 0;}bool isPalindrome(int x){
char sz[20]; sprintf(sz,"%d",x); printf("%s \n",sz); char *start = sz,*end = sz; while(*end) {
end ++; } end--; while(start <= end) {
if(*start == *end) {
start++; end--; } else {
return false; } } return true;}
  • 方法二:
bool isPalindrome(int x){
int y = x,temp ; long res = 0; if(x < 0) {
return false; } do{
temp = y % 10; res = res *10 + temp; y /= 10; }while(y != 0); printf("%d \n",res); if(res == x) {
return true; } else {
return false; }}

分析总结

  • 对于数字而言,可以有效模拟出栈和入栈,出栈就是“%10”,同时原数“/10”。入栈就是原数“*10”,加上后来的数字
  • 对于将整型数字转成字符串,建议用sprintf()函数

solution的分析

  • 首先题目已经说明不可以将整型数字转成字符串,转成字符串会产生很多的非永久的存储空间。
  • 然后,如果将原来的数字进行反转,直接和原来的数字进行比较会出现越界的情况
  • 最后,为了防止越界,但又不创建字符串,就反转原来的数字一半,在和剩余的另外一半进行比较。
代码实现
  • 步骤一:不是回文的:负数 或者 最后一位是零而末尾不是零的
  • 步骤二:反转原数的一半,当且仅当原数 “<="反转之后的数字
  • 步骤三:判定是否相等:原数 == 反转之后的数字 或者 反转之后的数字 / 10 == 原数(针对12321之类的,偶数的个数)

代码实现

int revert = 0;    if( x < 0 || (x% 10 == 0 && x != 0))    {
return false; } while(x > revert) {
revert = revert * 10 + x % 10; x /= 10; } if(x == revert ||(x == (revert / 10))) {
return true; }

总结

  • 思考问题的方式有待改善

转载地址:http://sggpb.baihongyu.com/

你可能感兴趣的文章
【C++】三、const与字符串
查看>>
【C++】四、重载,重写,重定义
查看>>
【C++】五、拷贝构造与赋值构造
查看>>
【C++】六、继承与多态
查看>>
特征向量的欧式距离与余弦距离——推荐算法
查看>>
cJSON源码分析3-核心解析算法
查看>>
如何正确使用C中的可变参数
查看>>
SDL2.0-简介
查看>>
SDL2.0-播放YUV文件
查看>>
leetcode 1.TwoSum--hashmap
查看>>
leetcode 14. Longest Common Prefix
查看>>
leetcode 26. Remove Duplicates from Sorted Array
查看>>
leetcode 27. Remove Element
查看>>
leetcode 66. Plus One
查看>>
leetcode 111. Minimum Depth of Binary Tree
查看>>
leetcode 257. Binary Tree Paths
查看>>
poj1611-并查集
查看>>
Trie树(字典树)
查看>>
大数运算-模拟
查看>>
腾讯2017暑假实习笔试题-字符串编码
查看>>