zoukankan      html  css  js  c++  java
  • 【LeetCode】13.Palindrome Number

    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.

    负数都不是回文数。判断回文数首先想到的是hints中的两个做法。分别用两种做法试了下,都A了,不知道是不是判定系统有没有考虑the restriction of using extra space。

    下面三种方法第三种最快。

    1、转换为字符串 java 1304 ms

    public class Solution {
        public boolean isPalindrome(int x) {
            // Note: The Solution object is instantiated only once and is reused by each test case.
            String num = String.valueOf(x);
            return new StringBuffer(num).reverse().toString().equalsIgnoreCase(num);
        }
    }
    

    2、Reverse Integer   cpp 328 ms  java 1340 ms

    public class Solution {
        public boolean isPalindrome(int x) {
            // Note: The Solution object is instantiated only once and is reused by each test case.
            int temp = x,n=0;
            if (x < 0)
                return false;
            if (x == 0)
                return true;
            while (temp>0)
            {
                n = n*10+temp%10;
                temp = temp/10;
            }
            return (x == n);
        }
    }
    

     注意:java中不能写while (temp),会出现编译错误,C++可以。

    3、最左最右逐位比较 cpp 268 ms  java 1180ms  

    public class Solution {
        public boolean isPalindrome(int x) {
            // Note: The Solution object is instantiated only once and is reused by each test case.
            int temp = x,n=0;
            if (x < 0)
                return false;
            if (x == 0)
                return true;
            int base=1;
            while(x/base>=10) 
                base*=10;
            while(x>0){
                int left=x/base;
                int right=x%10;
                if(left!=right)
                    return false;
                x-=base*left;
                x/=10;
                base/=100;
            }
            return true;
        }
    }
    

      

  • 相关阅读:
    wikioi 1002 旁路
    OS X升级到10.10使用后pod故障解决方案出现
    Python challenge 3
    maven 编
    独立博客网站FansUnion.cn操作2多年的经验和教训以及未来计划
    Wakelock API详解
    智遥工作流——会签与多人审批区别
    mysql 参数optimizer_switch
    OpenRisc-31-关于在设计具有DMA功能的ipcore时的虚实地址转换问题的分析与解决
    TROUBLE SHOOTING: FRM-30425
  • 原文地址:https://www.cnblogs.com/guozhiguoli/p/3373720.html
Copyright © 2011-2022 走看看