Palindrome number Java implementation

pg88888 2022-01-26 19:36:19 阅读数:740

palindrome number java implementation

  Palindrome number :

        " Palindrome number " It's a number . Such as :98789, This number is reading 98789, Back reading is also 98789, It's like reading backwards , So this number is the palindrome number  

Java Realization :

        The main idea is to convert the given number into a string , Then convert the string into a character array , By comparing the corresponding two digits before and after the character array ( Such as ”123321“ Is to compare 1-1,2-2,3-3), The whole cycle , The corresponding numbers are all equal , That's the palindrome number , If there is an inequality , That's not palindrome number ;

Tips:

        What you need to know in advance is negative numbers 、10 And 10 Multiple 、 Negative numbers are not palindromes ;

public class Demo4 {
public static boolean a(int x) {
if(x==0){return true;} // determine 0 It's palindrome number
else if (x < 0 || x % 10 == 0) { // Negative numbers are not palindromes ;x%10==0 As long as it is 10 Multiple , Definitely not palindromes ( You can actually put x%10==0 Get rid of , The main reason why it is not removed is that it can improve the computing speed of the computer );
return false;
}
else{
String string = String.valueOf(x); // hold x Convert to string ;
char[] ch = string.toCharArray(); // Convert string to character array ;
for (int i = ch.length-1; i >0; i--) {
if (ch[i] == ch[ch.length-1-i]){ // Judge whether the two corresponding numbers are equal , Do not consider odd or even numbers ;
continue; // If equal, continue the no loop ;
}else {
return false; // As long as there is a set of inequality, jump out of the loop ;
}
}
return true; // Whole for If the loop succeeds, it turns out to be the palindrome number
}
}
public static void main(String args[]){
System.out.println(Demo4.a(123321));
}
}

copyright:author[pg88888],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/01/202201261936167240.html