LeetCode 9. Palindrome Number

来源:互联网 发布:免费男女交友软件 编辑:程序博客网 时间:2024/06/06 02:36

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


判断一个整数是不是回文结构。

首先想到的办法是利用反转整数,判断翻转后和原始整数是否相等。

public class Solution {    public boolean isPalindrome(int x) {        if(x<0){            return false;        }        long a = reverse(x);        if(a==x){            return true;        }        return false;    }    public long reverse(int x){        long a = 0;        while(x!=0){            a = a*10 + x%10;            x = x/10;        }        return a;    }}
程序可以通过,不过发现排名很低,看了下前面的代码,发现了差距所在:

public class Solution {    public boolean isPalindrome(int x) {        if(x<0){            return false;        }        if(x<10){            return true;        }        if(x%10==0){            return false;        }        int a = 0;        while(x!=0){            a = a*10 + x%10;            x = x/10;            if(a!=0&&(a==x||a==x/10)){                return true;            }        }        return false;    }}
可以先判断是否为负、是否是个位数、个位是否为0来进行筛选,剩下的只需要进行一半的循环判断,即x的位数还剩一半时,逆序数和原始数是应该相等的,这样可以节省很多时间。


0 0
原创粉丝点击