JavaAlgorithms/Maths/PalindromeNumber.java

31 lines
758 B
Java
Raw Normal View History

2019-10-11 16:17:38 +08:00
package Maths;
public class PalindromeNumber {
2020-10-24 18:23:28 +08:00
public static void main(String[] args) {
2019-10-11 16:17:38 +08:00
2020-10-24 18:23:28 +08:00
assert isPalindrome(12321);
assert !isPalindrome(1234);
assert isPalindrome(1);
}
2019-10-11 16:17:38 +08:00
2020-10-24 18:23:28 +08:00
/**
* Check if {@code n} is palindrome number or not
*
* @param number the number
* @return {@code true} if {@code n} is palindrome number, otherwise {@code false}
*/
public static boolean isPalindrome(int number) {
if (number < 0) {
throw new IllegalArgumentException(number + "");
}
int numberCopy = number;
int reverseNumber = 0;
while (numberCopy != 0) {
int remainder = numberCopy % 10;
reverseNumber = reverseNumber * 10 + remainder;
numberCopy /= 10;
2019-10-11 16:17:38 +08:00
}
2020-10-24 18:23:28 +08:00
return number == reverseNumber;
}
2019-10-11 16:17:38 +08:00
}