[LeetCode]9.Palindrome Number


【题目】

Determine whether an integer is a palindrome. Do this without extra space.

click to show spoilers.

Some hints:

Could negative integers be palindromes? (ie, ⑴)

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.

【分析】

将整数反转,然后与原来的数比较,如果相等则为Palindrome Number否则不是

【代码】

/*********************************
* 日期:2015-01⑵0
* 作者:SJF0115
* 题目: 9.Palindrome Number
* 网址:https://oj.leetcode.com/problems/palindrome-number/
* 结果:AC
* 来源:LeetCode
* 博客:
**********************************/
#include <iostream>
using namespace std;

class Solution {
public:
bool isPalindrome(int x) {
// negative integer
if(x < 0){
return false;
}//if
int tmp = x;
int n = 0;
// reverse an integer
while(tmp){
n = n * 10 + tmp % 10;
tmp /= 10;
}//while
return (x == n);
}
};

int main(){
Solution solution;
int num = 1234321;
bool result = solution.isPalindrome(num);
// 输出
cout<<result<<endl;
return 0;
}

【分析2】

上1种思路,将整数反转时有可能会溢出。

这里的思路是不断的取第1位和最后1位(10进制)进行比较,相等则取第2位和倒数第2位…….直到完成比较或中途不相等退出。

【代码2】

class Solution {
public:
bool isPalindrome(int x) {
// negative integer
if(x < 0){
return false;
}//if
// 位数
int divisor = 1;
while(x / divisor >= 10){
divisor *= 10;
}//while
int first,last;
while(x){
first = x / divisor;
last = x % 10;
// 高位和低位比较 是不是相等
if(first != last){
return false;
}//if
// 去掉1个最高位和1个最低位
x = x % divisor / 10;
divisor /= 100;
}//while
return true;
}
};

波比源码 – 精品源码模版分享 | www.bobi11.com
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需!
7. 本站源码并不保证全部能正常使用,仅供有技术基础的人学习研究,请谨慎下载
8. 如遇到加密压缩包,请使用WINRAR解压,如遇到无法解压的请联系管理员!

波比源码 » [LeetCode]9.Palindrome Number

发表评论

Hi, 如果你对这款模板有疑问,可以跟我联系哦!

联系站长
赞助VIP 享更多特权,建议使用 QQ 登录
喜欢我嘛?喜欢就按“ctrl+D”收藏我吧!♡