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

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

  • 相关阅读:
    运维岗春招--part2
    python 题库|刷题
    leetcode刷题
    运维面经汇总
    python自动化运维阅读笔记
    Python编程汇总
    old_boy 运维学习-第一期
    团队博客作业-Week3
    个人对final发布产品的排名
    各组对final发布产品的排名
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/10147127.html
Copyright © 2011-2022 走看看