当前位置:网站首页>Leetcode - number of palindromes

Leetcode - number of palindromes

2022-07-25 01:20:00 Programmer Xiangzai

Topic information

source address : Palindrome number

Give you an integer x, If x Is a palindrome integer , return true; otherwise , return false.

Palindrome number refers to positive order ( From left to right ) Reverse order ( From right to left ) Read all the same integers .

for example ,121 It's palindrome. , and 123 No .

Prompt information

Example 1

 Input :x = 121
 Output :true

Example 2

 Input :x = -121
 Output :false
 explain : Read left to right ,  by  -121 .  Read right to left ,  by  121- . So it's not a palindrome number .

Example 3

 Input :x = 10
 Output :false
 explain : Read right to left ,  by  01 . So it's not a palindrome number .

Tips

  • -2^31 <= x <= 2^31 - 1

Implementation logic

Double pointer

The simpler way of thinking is , First convert an integer into a string , Then use the first and last double pointers to determine whether the characters at the indicated position are the same , Until all the characters are compared .

 Palindrome number 01

As shown in the figure above , Using double pointers is an intuitive idea , It's important to note that , Negative integers are not palindromes , There is a difference between odd and even numbers in palindrome judgment .

package cn.fatedeity.algorithm.leetcode;

public class PalindromeNumber {
    public boolean answer(int x) {
        if (x < 0) {
            return false;
        }
        //  Convert to string 
        String s = Integer.toString(x);
        //  Double pointer judgment 
        int len = s.length();
        for (int i = 0; i < len >> 1; i++) {
            if (i != len - 1 - i && s.charAt(i) != s.charAt(len - 1 - i)) {
                return false;
            }
        }
        return true;
    }
}

Do not convert to string

If you add the limitation that integers cannot be converted into strings to this problem , We need to think about the solution from the perspective of Mathematics .

Since you want to judge whether an integer is a palindrome , You can directly turn an integer into another integer , Then match these two integers equally , This method has more cycles than double pointers , But it takes no time to convert integers into strings , Integer efficiency is higher .

package cn.fatedeity.algorithm.leetcode;

public class PalindromeNumber {
    public boolean answer(int x) {
        if (x < 0) {
            return false;
        }
        //  Flip integers 
        int reverse = 0;
        int rest = x;
        while (rest >= 10) {
            reverse = reverse * 10 + rest % 10;
            rest = (int) (rest / 10.0);
        }
        return reverse * 10 + rest == x;
    }
}
原网站

版权声明
本文为[Programmer Xiangzai]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/202/202207201213258944.html