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
Example 3:
Input: 10
Output: false
Follow up:
Coud you solve it without converting the integer to a string?
关键点:
1.负数均不是回文数
2.若为正数,则判断原数和翻转数是否相等。
3.函数返回值是bool变量,所以应该return true,而不是return “true”;
#include
#include<climits>
using namespace std;
stringinverse(intx){
if(x<0)
return"false";
intnewnum=0,oldnum=x;
while(oldnum!=0)
{
newnum=newnum*10+oldnum%10;
oldnum=oldnum/10;
}
if(x==newnum)
return"true";
else
return"false";
}
intmain(intargc,constchar* argv[]) {
// insert code here...
inta;
while(cin>>a){
cout<
}
cout << "Hello, World!\n";
return 0;
}
网上其他的代码,其思路:每次提取头尾两个数,判断它们是否相等,判断后去掉头尾两个数
class Solution {
public:
bool isPalindrome(int x) {
//negative number
if(x < 0)
return false;
int len = 1;
while(x / len >= 10)
len *= 10;
while(x > 0) {
//get the head and tail number
int left = x / len;
int right = x % 10;
if(left != right)
return false;
else {
//remove the head and tail number
x = (x % len) / 10;
len /= 100;
}
}
return true;
}
};
网友评论