首页 > 其他 > 详细

Leetcode[9]-Palindrome Number

时间:2015-06-13 09:47:59      阅读:232      评论:0      收藏:0      [点我收藏+]

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.

Leetcode链接:https://leetcode.com/problems/palindrome-number/


思路:求出它的反转数,然后比较两个数是否恒等于即可。

代码:

class Solution {
public:
    bool isPalindrome(int x) {

        if(x < 0) return false;
        int y = x, result = 0;
        while( y > 0 ){
            result = result * 10 + y%10;
            y /= 10;
        }
        return result == x;
    }
};

法二:将数字转换成字符串,遍历一遍字符串,看首位是否相等即可

    bool isPalindrome(int x) {

        if(x < 0) return false;
        if(x>=0 && x<=9) return true;
        string str;
        stringstream ss;
        ss<<x;
        ss>>str;
        int len = str.length();
        for(int i = 0; i < (len/2); i++ ){
            if(str[i] != str[len-1-i])return false;
        }
        return true;

    }

Leetcode[9]-Palindrome Number

原文:http://blog.csdn.net/dream_angel_z/article/details/46480453

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!