A palindrome number is a number whose reverse order is the same as the original number.
Even Palindrome: In this the number of elements in the palindrome is even and there is no middle element of the number.
In this example, there are 6 digits. We have to compare elements with index 0 with 5, 1 with 4 and 2 with 3. If they match then it is a palindrome. So in short we just have to check 6/2=3 conditions.
Odd Palindrome: In this the number of elements in the palindrome is odd and there is a middle element of the number.
In this example, there are 5 digits and there is a middle element. We have to compare elements with index 0 with 4, and 1 with 3. If they match then it is a palindrome. No need to check the middle element as it can be anything. So in short we just have to check Integer(5/2)=Integer(2.5)=2 conditions.
Algorithm: Let n be the number. Input the number as a string.
Step 1: Initialize a variable i = 0
Step 2: If i <(n.length()/2) then go to Step 3 else go to Step 6
Step 3: If n.charAt(i) != n.charAt(n.length()-1-i) then goto Step 4 else goto Step5
Step 4: return "Not Palindrome"
Step 5: i = i+1 goto Step 2
Step 6: return "Palindrome"
Example:
1) n = 274472 n.length()/2 = 6/2 = 3
Step 1: i = 0
Iteration 1 :
Step 2: 0<3 then go to Step 3
Step 3: Here n.length()-i-1 = 6-0-1 = 5 and n.charAt(0) == n.charAt(5) goto Step 5
Step 5: i = 0+1 = 1 goto Step 2
Iteration 2 :
Step 2: 1<3 then go to Step 3
Step 3: Here n.length()-i-1 = 6-1-1 = 4 and n.charAt(1) == n.charAt(4) goto Step 5
Step 5: i = 1+1 = 2 goto Step 2
Iteration 3 :
Step 2: 2<3 then go to Step 3
Step 3: Here n.length()-i-1 = 6-2-1 = 3 and n.charAt(2) == n.charAt(3) goto Step 5
Step 5: i = 2+1 = 3 goto Step 2
Iteration 4 :
Step 2: 3 is not less than 3 then go to Step 6
Step 6: return "Palindrome".
2) n = 27472 n.length()/2 = Integer(5/2) = 2
Step 1: i = 0
Iteration 1:
Step 2: 0<2 then go to Step 3
Step 3: Here n.length()-i-1 = 5-0-1 = 4 and n.charAt(0) == n.charAt(4) goto Step 5
Step 5: i = 0+1 = 1 goto Step 2
Iteration 2:
Step 2: 1<2 then go to Step 3
Step 3: Here n.length()-i-1 = 5-1-1 = 3 and n.charAt(1) == n.charAt(3) goto Step 5
Step 5: i = 1+1 = 2 goto Step 2
Iteration 3:
Step 2: If 2 is not less than 2 then go to Step 6
Step 6: return "Palindrome"
3) n = 27432 n.length()/2 = Integer(5/2) = 2
Step 1: i = 0
Iteration 1:
Step 2: 0<2 then go to Step 3
Step 3: Here n.length()-i-1 = 5-0-1 = 4 and n.charAt(0) == n.charAt(4) goto Step 5
Step 5: i = 0+1 = 1 goto Step 2
Iteration 2:
Step 2: 1<2 then go to Step 3
Step 3: Here n.length()-i-1 = 5-1-1 = 3 and n.charAt(1) != n.charAt(3) goto Step 4
Step 4: return "Not Palindrome"
Time Complexity: If n is the length of the string then we need n/2 operations to find whether it is palindrome or not. Hence T(n) = O(n/2) = O(n)
Code: JAVA