【LeetCode】009 Palindrome Number

题目:LeetCode 009 Palindrome Number

题意:判断一个整数是否为回文数,不要用额外空间

思路:我不会不用额外空间的方法,需要利用一个长度为20以内的字符串。将整数先写入一个字符串,然后判断首位字符是否相等即可。

代码如下:

 1 class Solution {
 2 public:
 3     bool isPalindrome(int x) {
 4         string s = to_string(x);
 5         int len = s.size();
 6         for(int i = 0; i < len-i-1; i++)
 7         {
 8             if(s[i] != s[len-i-1]) 
 9                 return false;
10         }
11         return true;
12     }
13 };

舍友睡觉前给想出来不用额外空间的方法,好腻害~~ 

思路:从末位数开始每次乘10再加次末位。

代码如下:

 1 class Solution {
 2 public:
 3     bool isPalindrome(int x) {
 4         if(x < 0) return false;
 5         int n = x, ans = 0;
 6         while(n)
 7         {
 8             ans *= 10;
 9             ans += (n%10);
10             n = n/10;
11         }
12         return ans == x;
13     }
14 };
原文地址:https://www.cnblogs.com/kathyrine/p/4460993.html