码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode[9]-Palindrome Number

时间:2015-06-13 09:48:14      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:extra   string   number   palindrome   回文数   

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

标签:extra   string   number   palindrome   回文数   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!