[LeetCode]9.Palindrome Number
來源:程序員人生 發(fā)布時間:2015-03-07 13:19:44 閱讀次數(shù):4006次
【題目】
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.
【分析】
將整數(shù)反轉(zhuǎn),然后與原來的數(shù)比較,如果相等則為Palindrome Number否則不是
【代碼】
/*********************************
* 日期:2015-01⑵0
* 作者:SJF0115
* 題目: 9.Palindrome Number
* 網(wǎng)址:https://oj.leetcode.com/problems/palindrome-number/
* 結(jié)果: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種思路,將整數(shù)反轉(zhuǎn)時有可能會溢出。
這里的思路是不斷的取第1位和最后1位(10進制)進行比較,相等則取第2位和倒數(shù)第2位.......直到完成比較或中途不相等退出。
【代碼2】
class Solution {
public:
bool isPalindrome(int x) {
// negative integer
if(x < 0){
return false;
}//if
// 位數(shù)
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;
}
};

生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學習有所幫助,可以手機掃描二維碼進行捐贈