leetcode 9. Palindrome Number

来源:互联网 发布:橙鑫数据科技靠谱吗 编辑:程序博客网 时间:2024/06/16 05:01

Determine whether an integer is a palindrome. Do this without extra space.

click to show spoilers.

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.

这道题题意很简单,就不说了,注意题目要求不可以使用额外的空间,也就是使用字符串判断是不可以的,那么可以直接计算出最高位和最低位来判断相等与否来实现回文数的判断,注意我们是判断整数的相等,所以相关除法等计算要注意按照整数来计算,否者可能会出错。

代码如下:

import java.util.ArrayList;public class Solution {    public boolean isPalindrome(int x)     {        if(x<0)            return false;        else if(x<=9)            return true;        int numOfDigits=0;        int tmp=x;        while(tmp!=0)        {            tmp=tmp/10;            numOfDigits++;        }        tmp=x;        int len=numOfDigits;        for(int i=0;i<numOfDigits/2;i++)        {            if((int)tmp%10 == (int)tmp/(int)Math.pow(10, len-1))            {                tmp=(int) (tmp%Math.pow(10, len-1));                tmp=tmp/10;                len=len-2;            }else                 return false;        }        return true;    }    public static void main(String[] args)     {        Solution solution = new Solution();        System.out.println(solution.isPalindrome(11));    }}

下面的是C++做法,我这里是使用字符串来做的。

代码如下:

#include <iostream>#include <sstream>using namespace std;class Solution {public:    bool isPalindrome(int x)     {        stringstream ss;        ss << x;        string res = "";        ss >> res;        int beg = 0, end = res.length() - 1;        while (beg < end)        {            if (res[beg] != res[end])                return false;            else            {                beg++;                end--;            }        }        return true;    }};
原创粉丝点击