Palindrome Number
Total Accepted: 57795 Total Submissions: 194286My Submissions
Question Solution
Determine whether an integer is a palindrome. Do this without extra space.
Hide Tags
Have you met this question in a real interview?
Yes
No
这题是简单题,但题目要求不要使用多余的内存空间,所以做时还是要想想,我是在开始是先计算出数的位数
然后每次比较是否回文时,就单独取出第i位,即先模再除就可以取出来了。
#include<iostream> #include<string> #include <math.h> using namespace std; int weishu(int x) { for(int i=0;i<=11;i++) if((x/(int)pow(10.0,i))==0) return i; } bool isPalindrome(int x) { if(x<0) return false; int len=weishu(x); for(int i=0;i<len/2;i++) if((x%(int)pow(10.0,i+1))/(int)pow(10.0,i) !=(x%(int)pow(10.0,len-1-i+1))/(int)pow(10.0,len-1-i)) return false; return true; } int main() { cout<<isPalindrome(121)<<endl; int x=121; int len=weishu(x); cout<<len<<endl; for(int i=0;i<len/2;i++) { cout<<(x%(int)pow(10.0,i+1))/(int)pow(10.0,i)<<endl; cout<<(x%(int)pow(10.0,len-1-i+1))/(int)pow(10.0,len-1-i)<<endl; } }
时间: 2024-08-02 08:19:23