Problem Statement:
Given a number , find the next Palindrome.
Solution:
Concept:
Please refer to Source Code
This is one of the many ways of getting the next Palindrome number w.r.t a given number.
Any comment or suggestion for any kind of code optimization or any other better approach is most welcome.
Happy Coding !! :)
Given a number , find the next Palindrome.
Solution:
Concept:
- Convert number to String.
- Take base as 1, which will be used to get left and right pointers, in subsequent steps,
- Multiple Base by 10 at even iteration of loop till half the length of the string.
- Take right and left pointer pointing to left and right digits in the string.
- Add the difference of left and right to the number
- if right is greater left the number would become smaller, therefore increment the next digit to the left of right.
- If the number is even and left and right pointer points to adjacent digits, increment right pointer
Please refer to Source Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | /** * Get next pallindrome * @param num * @return */ public static int nextPanlindrome( int num) { if (isPalindrome(num)) //skip if number entered is pallindrome num++; String temp = num + "" ; int end=temp.length() - 1 ; int base= 1 ; for ( int start = 0 ; start < end; start++, end--) { // Gives the right digit int right = Integer.parseInt(temp.charAt(end)+ "" ) * base; // Gives the left digit int left = Integer.parseInt(temp.charAt(start)+ "" ) * base; // add differnce to the number num = num + left - right ; //------(1) base *= 10 ; if (right > left) { num += base; // for incresing the value of number which got decreased at (1) // previous step indroduces asymmetry if its a even number. if (start == end - 1 ) // For even numbers eg. case 8468 (adjacent digits) num += base/ 10 ; } temp = num + "" ; } return num; } public static boolean isPalindrome( int num) { int reverse = 0 , temp=num; while ( temp != 0 ) { reverse = reverse * 10 ; reverse = reverse + temp% 10 ; temp = temp/ 10 ; } return (num == reverse ? true : false ); } |
This is one of the many ways of getting the next Palindrome number w.r.t a given number.
Any comment or suggestion for any kind of code optimization or any other better approach is most welcome.
Happy Coding !! :)
No comments:
Post a Comment