zoukankan      html  css  js  c++  java
  • 9. Palindrome Number

    Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

    Example 1:

    Input: 121
    Output: true
    

    Example 2:

    Input: -121
    Output: false
    Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
    

    Example 3:

    Input: 10
    Output: false
    Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

    Follow up:

    Coud you solve it without converting the integer to a string?

    如果可以用string,那么就可以

    public boolean isPalindrome(int x) {
            String input  = String.valueOf(x);
            return Objects.equals(input, new StringBuilder(input).reverse().toString());
        }
    

      

    笨方法1:

    Reverse integer 然后和原数字对比,如果对就是true。

    class Solution {
        public boolean isPalindrome(int x) {
            boolean a = false;
            int res=0;
            int med = x;
            if(x<0||x%10==0){
                a =  false;
            }
            while(med>0){
                res = res*10+ med%10;
                med/=10;
            }
            if(x==res)
                a=true;
            return a;
          
        }
    }

    方法2:

    只用取出后一半的数字,和前一半的数字进行对比,如果相等则返回true

    class Solution {
        public boolean isPalindrome(int x) {
     if (x < 0 || (x % 10 == 0 && x != 0)) return false;
            int revertNum = 0;
            while (x > revertNum) {
                revertNum = revertNum * 10 + x % 10;
                x /= 10;
            }
            return x == revertNum || x == revertNum / 10;
        }
    }
    

      这种方法比上面的理论上快一倍。

  • 相关阅读:
    轮播插件unsilder 源码解析(二)
    轮播插件unsilder 源码解析(一)---源码解析
    轮播插件unsilder 源码解析(一)---使用
    jquery插件扩展的学习
    基于canvas的陈列订货的分析
    grunt安装和使用教程
    2016订货会项目总结2
    2016工作项目完成总结
    不使用递归法求值
    easy bootstrap模板
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/10147127.html
Copyright © 2011-2022 走看看