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;
        }
    }
    

      

  • 相关阅读:
    jumpserver的安装
    安装iostat 命令
    zabbix配置server,proxy,agent架构
    RGB颜色对照表
    【ZYNQ-7000开发之九】使用VDMA在PL和PS之间传输视频流数据
    基于AXI VDMA的图像采集系统
    图像采集调试总结
    DDR3调试总结
    内存系列二:深入理解硬件原理
    在嵌入式设计中使用MicroBlaze(Vivado版本)
  • 原文地址:https://www.cnblogs.com/guozhiguoli/p/3373720.html
Copyright © 2011-2022 走看看