An algorithm for determining the palindrome number of O (1) In space complexity
To realize the spatial complexity of O (1) palindrome number determination, input is the integer constant, the output is required to determine whether the palindrome number.
The required format is as follows:
Public boolean ispalindrome (int x) { //Your Judge code }
Second, the concept
Palindrome number (palindrome) definition: set N is an arbitrary natural number. If the numbers of n are reversed and the natural number N1 is equal to N, then N is a palindrome number. For example, if n=1234321, then n is a palindrome number, but if n=1234567, then n is not a palindrome number.
Characteristics:
1. Negative numbers, decimals are not palindrome numbers;
2. Palindrome can be an odd number or even a number of numbers;
Third, analysis
According to the definition of palindrome number, we should pay attention to the following points in the design of the program in this subject:
1. When the number of palindrome inverted after the overflow may exist;
2. The spatial complexity of O (1) requires variable definition number can not be too many, if an input, then the custom variable should be defined as 1 and within;
Four, the algorithm
Set the input data to X.
1. If x is less than 0 or x is 10 N (n>=1), the return is false;
2. Set the comparison variable rev for 0,rev each increment of the last digit of x and X to remove the last digit each time, if Rev is less than or equal to X, then continue 2 steps, otherwise enter step 3;
3. Output The final result, if Rev equals X or Rev except 10 rounding equals X, then x is a palindrome number, otherwise it is not a palindrome number.
V. Java code
Public classPalindromenumber { Public Static voidMain (string[] args) {Palindromenumber P=NewPalindromenumber (); System.out.println (P.ispalindrome (32233223)); } Public BooleanIspalindrome (intx) {if(X < 0 | | (x! = 0 && x% 10 = = 0)) { return false; } intRev = 0; while(X >rev) {Rev= Rev * + x% 10; X= X/10; } return(x = Rev | | x = = REV/10); }}
Six, advantages
1. The algorithm defines only an additional temporary variable rev, without defining a string and then comparing it by loop;
2. Through the continuous growth of rev and the shortening of X, the two end up to the length of X/2, no overflow situation;
3. The performance is very high, the occupied time space is very low.
An algorithm for determining palindrome numbers with space complexity of O (1)