Determine whether an integer is a palindrome. Do this without extra space.
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.
【解答】Palindrome指的是回文,而这里需要找的是回文数,指的是1、121、34543这样从左往右看和从右往左看都相等的数。先找到数字总共有几位,然后判断高位和低位是否相等,相等是回文数。
主要思路在于怎么去数据的最高位、次高位 最低位和次低位;
#include<iostream> #include<string> #include<algorithm> using namespace std; int main() { int n = 1234567891; int d = 0; int m = n; bool isrome=true; while (m != 0) { d++; m = m/ 10; } //下面怎么取数据的最后一位 和第一位 最后一位%10 头一位n/pow(10,d) while (n) { int first = n / pow(10, d-1); int last = n % 10; if (first != last) isrome = false; //怎么对n进行数据的更新 去头 去未 int k = pow(10, d-1); n = n%k / 10; d=d-2; } cout << d <<" "<<n<<" "<<isrome<<endl; system("pause"); return 0; }
别人的代码:
public class Solution { public boolean isPalindrome(int x) { if (x < 0) return false; //calcu the length of digit int len = 1; while (x / len >= 10) { len *= 10; } while (x != 0) { int left = x / len; int right = x % 10; if (left != right) return false; //remove the head and tail digit x = (x % len) / 10; len /= 100; } return true; } }
class Solution { public: bool isPalindrome(int x) { if (x < 0) return false; if (x < 10) return true; int digits = 0; int t = x; int d = 0; while(t != 0) t /= 10, ++d; int left = pow(10, d - 1); int right = 1; while( left >= right) { if (x / left % 10 != x / right % 10) return false; left /= 10; right *= 10; } return true; } };
class Solution { public: bool isPalindrome(int x) { // Start typing your C/C++ solution below // DO NOT write int main() function if (x < 0) return false; if (x == 0) return true; int base = 1; while(x / base >= 10) base *= 10; while(x) { int leftDigit = x / base; int rightDigit = x % 10; if (leftDigit != rightDigit) return false; x -= base * leftDigit; base /= 100; x /= 10; } return true; } };
#include<iostream> #include<algorithm> using namespace std; bool judge(int n); int main() { int a[] = { 111, 23, 454, 678876 }; for (int i = 0; i < sizeof(a) / sizeof(a[0]); i++) { cout << judge(a[i]) << endl; } system("pause"); return 0; } bool judge(int n) { //首先得判断最高位是多少 if (n < 10 && n>0) return true; if (n == 0) return true; int base = 1; while ((n / base) >= 10) { base *= 10; } while (n>0) { int left = n / base; int right = n % 10; if (left != right) return false; n = (n%base) / 10; base = base / 100; } return true; }