Leetcode刷题Day3 Palindrome Number

来源:互联网 发布:孩子网络借贷怎么办 编辑:程序博客网 时间:2024/05/29 18:11

题目: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.

我自己的做法:根据提示,无论输入什么整数先变换为字符串,然后用two pointers的思想,两个指针一头一尾向中间扫描。对比一头一尾两个字符是否相等,若相等则继续向里扫描。若不相等则返回false不必再继续向中间扫描。

public class Main {    public static void main(String[] args) {     System.out.print(isPalindrome(1000021 ));    }    public static boolean isPalindrome(int x) {        String str = Integer.toString(x);        int length = str.length();        int halflen= length/2+1;       // System.out.println("length is"+length);        for(int i=0;i<halflen;i++)        {            if(str.charAt(i)!=str.charAt(length-1-i))            {                return  false;            }        }        return true;    }}

我觉得最有意思的莫过于此:

就是我AC的时间跑了293ms,竟然只打过了10%的选手,于是我开始学习更优化的做法

别人的做法,基于分类讨论,并没有转化为字符串:

public class Solution {    public boolean isPalindrome(int x) {         if (x<0 || (x!=0 && x%10==0)) return false;//如果是负数,或者是尾数是0的数字,肯定不是回文数。因为个位是0的数,如果想成为回文数,第一位也是0,这是不可能的。所以0也不是回文数    int rev = 0;//代表回文的内容    while (x>rev){     rev = rev*10 + x%10;//由此可知rev的顺序是 第一位-->前两位-->前三位 大概截止到回文中点     x = x/10;//由此可知x顺序为 全部-->舍去最后一位的x-->舍去最后两位的x 大概截止到回文中点     }    return (x==rev || x==rev/10);//x==rev对应偶数位输入  x==rev/10对应奇数位输入    }}

这个做法跑了209/187ms,打败了60%/93.55%的选手(同一个算法每次运行时间也不尽相同),算法构思巧妙


第三种做法:是Submission里最快的,只跑了159ms

public class Solution {    public boolean isPalindrome(int x) {if (x < 0) return false;long original = x;long result = 0; while (x != 0) {result = result*10 + x%10;x /= 10;}return original == result;    }}

算法思想很笨,就是不管输入x是什么,只要不是负数就先倒过来,倒完了以后再跟输入比。

莫名竟然最快,为什么呢?

原创粉丝点击