首页 > 其他 > 详细

Leetcode#9Palindrome Number

时间:2015-05-06 01:35:23      阅读:215      评论:0      收藏:0      [点我收藏+]

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

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

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