博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode练习-数组-palindrome-number
阅读量:4092 次
发布时间:2019-05-25

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

题目描述

Determine whether an integer is a palindrome. Do this without extra space.
click to show spoilers.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.

思路1:先算出数字的位数,然后循环比较对应位数字是否相同,若相同,则继续比较;若不同,则返回false。

思路2:反转数字(注意溢出问题)

代码:

#include
#include
using namespace std;bool isPalindrome(int x);bool isPalindrome_2(int x);int main(){ cout << isPalindrome(100801) << endl; return 0;}bool isPalindrome(int x){ if(x < 0) return false; int count = 1; int a = x; while(a/10 != 0){//计算数字位数 ++count; a = a/10; } int tenH = pow(10, count - 1);//初始化tenH,用来计算高位数字 int tenL = int(pow(10, 1));//初始化tenL,用来计算低位数字 int i; for(i = 1; i <= count/2; ++i){ //int h = x / pow(10, count - i); int h = x / tenH; tenH = tenH / 10;//更新tenH if(h >= 10) h = h % 10; //int l = x % int(pow(10, i)); //l = l / int(pow(10, i-1)); int l = x % tenL; l = l / (tenL / 10); tenL = tenL * 10;//更新tenL //cout << "h: " << h << " l: " << l << endl;//测试输出 if(h != l)//比较对应位 return false; } return true;}bool isPalindrome_2(int x) { int res=0; int tmp=x; if(x<0) return false; while(tmp) { res=res*10+tmp%10;//此公式可自动处理末尾为0而逆反带来的溢出问题 tmp/=10; } if(res==x) return true; else return false;}

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

你可能感兴趣的文章
Git操作清单
查看>>
基础算法
查看>>
前端面试
查看>>
JavaScript实现DOM树的深度优先遍历和广度优先遍历
查看>>
webpack4 中的 React 全家桶配置指南,实战!
查看>>
react 设置代理(proxy) 实现跨域请求
查看>>
通过试题理解JavaScript
查看>>
webpack的面试题总结
查看>>
实践这一次,彻底搞懂浏览器缓存机制
查看>>
Koa2教程(常用中间件篇)
查看>>
React Hooks 完全指南
查看>>
nvm 和 nrm 的安装与使用
查看>>
React Redux常见问题总结
查看>>
总结vue知识体系之实用技巧
查看>>
PM2 入门
查看>>
Flutter ListView如何添加HeaderView和FooterView
查看>>
Flutter key
查看>>
Flutter 组件通信(父子、兄弟)
查看>>
Flutter Animation动画
查看>>
Android 混合Flutter之产物集成方式
查看>>