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

Leetcode#9Palindrome Number

时间:2015-05-06 01:37:13      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:problem   without   whether   solved   

Palindrome Number

 Total Accepted: 54885 Total Submissions: 185086My Submissions

Question Solution 


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.


Show Tags

分析:负数不是回文数字,而且题目要求不能有额外的空间,因此不能以字符串形式存储,因此可以=比对首位两个数字是否相等,比对后去除首尾数字,然后依次迭代,直到只剩1个数字或是不剩数字,返回结果


public class Solution {

    public boolean isPalindrome(int x) {

        if(x<0)

            return false;

            

        int p=1;

        while(x/p>=10)

            p=p*10;

        int q=10;

        while(p>1)

        {

            if(x/p!=x%q)

                return false;

            else

            {

                x=x%p;

                x=x/q;

                p=p/100;

            }

        }

        return true;

    }

}


Leetcode#9Palindrome Number

标签:problem   without   whether   solved   

原文地址:http://7061299.blog.51cto.com/7051299/1642288

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