Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
GeeksforGeeks
A computer science portal for geeks
Placements
Practice
GATE CS
IDE
Q&A
GeeksQuiz
Login/Register
We strongly recommend that you click here and practice it, before moving on
to the solution.
Solution for input type 1 is easy. The output contains n + 1 digits where the corner digits are 1, and all digits
between corner digits are 0.
Now let us rst talk about input type 2 and 3. How to convert a given number to a greater palindrome? To
understand the solution, let us rst dene the following two terms:
Left Side: The left half of given number. Left side of 1 2 3 4 5 6 is 1 2 3 and left side of 1 2 3 4 5 is 1 2
Right Side: The right half of given number. Right side of 1 2 3 4 5 6 is 4 5 6 and right side of 1 2 3 4 5 is 4 5
To convert to palindrome, we can either take the mirror of its left side or take mirror of its right side. However, if we
take the mirror of the right side, then the palindrome so formed is not guaranteed to be next larger palindrome. So,
we must take the mirror of left side and copy it to right side. But there are some cases that must be handled in
different ways. See the following steps.
We will start with two indices i and j. i pointing to the two middle elements (or pointing to two elements around the
middle element in case of n being odd). We one by one move i and j away from each other.
Step 1. Initially, ignore the part of left side which is same as the corresponding part of right side. For example, if the
number is 8 3 4 2 2 4 6 9, we ignore the middle four elements. i now points to element 3 and j now points to
element 6.
Step 2. After step 1, following cases arise:
http://www.geeksforgeeks.org/given-a-number-nd-next-smallest-palindrome-larger-than-this-number/
1/15
05/10/2016
//Autilityfunctiontoprintanarray
voidprintArray(intarr[],intn)
//Autilityfunctiontocheckifnumhasall9s
intAreAll9s(intnum[],intn)
//Returnsnextpalindromeofagivennumbernum[].
//Thisfunctionisforinputtype2and3
voidgenerateNextPalindromeUtil(intnum[],intn)
{
//findtheindexofmiddigit
intmid=n/2
//Aboolvariabletocheckifcopyofleftsidetorightissufficientornot
boolleftsmaller=false
//endofleftsideisalways'mid1'
inti=mid1
//Beginingofrightsidedependsifnisoddoreven
intj=(n%2)?mid+1:mid
//Initially,ignorethemiddlesamedigits
while(i>=0&&num[i]==num[j])
i,j++
//Findifthemiddledigit(s)needtobeincrementedornot(orcopyingleft
//sideisnotsufficient)
if(i<0||num[i]<num[j])
leftsmaller=true
//Copythemirroroflefttotight
http://www.geeksforgeeks.org/given-a-number-nd-next-smallest-palindrome-larger-than-this-number/
2/15
05/10/2016
//Copythemirroroflefttotight
while(i>=0)
{
num[j]=num[i]
j++
i
}
//Handlethecasewheremiddledigit(s)mustbeincremented.
//ThispartofcodeisforCASE1andCASE2.2
if(leftsmaller==true)
{
intcarry=1
i=mid1
//Ifthereareodddigits,thenincrement
//themiddledigitandstorethecarry
if(n%2==1)
{
num[mid]+=carry
carry=num[mid]/10
num[mid]%=10
j=mid+1
}
else
j=mid
//Add1totherightmostdigitoftheleftside,propagatethecarry
//towardsMSBdigitandsimultaneouslycopyingmirroroftheleftside
//totherightside.
while(i>=0)
{
num[i]+=carry
carry=num[i]/10
num[i]%=10
num[j++]=num[i]//copymirrortoright
}
}
}
//Thefunctionthatprintsnextpalindromeofagivennumbernum[]
//withndigits.
voidgenerateNextPalindrome(intnum[],intn)
{
inti
printf("\nNextpalindromeis:\n")
//Inputtype1:Allthedigitsare9,simplyo/p1
//followedbyn10'sfollowedby1.
if(AreAll9s(num,n))
{
printf("1")
for(i=1i<ni++)
printf("0")
printf("1")
}
//Inputtype2and3
else
{
generateNextPalindromeUtil(num,n)
//printtheresult
printArray(num,n)
}
}
//Autilityfunctiontocheckifnumhasall9s
intAreAll9s(int*num,intn)
{
inti
for(i=0i<n++i)
if(num[i]!=9)
return0
http://www.geeksforgeeks.org/given-a-number-nd-next-smallest-palindrome-larger-than-this-number/
3/15
05/10/2016
return0
return1
}
/*Utilitythatprintsoutanarrayonaline*/
voidprintArray(intarr[],intn)
{
inti
for(i=0i<ni++)
printf("%d",arr[i])
printf("\n")
}
//DriverProgramtotestabovefunction
intmain()
{
intnum[]={9,4,1,8,7,9,7,8,3,2,2}
intn=sizeof(num)/sizeof(num[0])
generateNextPalindrome(num,n)
return0
}
Run on IDE
Output:
Next palindrome is:
94188088149
Please write comments if you nd anything incorrect, or you want to share more information about the topic
discussed above.
Related Posts:
Find the minimum value of m that satises ax + by = m and all values after m also satisfy
Finding number of digits in nth Fibonacci number
Carmichael Numbers
Multiples of 3 or 7
Count Divisors of Factorial
Non Fibonacci Numbers
Find Last Digit Of a^b for Large Numbers
Reverse and Add Function
http://www.geeksforgeeks.org/given-a-number-nd-next-smallest-palindrome-larger-than-this-number/
4/15
05/10/2016
Writing code in comment? Please use code.geeksforgeeks.org, generate link and share the link here.
56 Comments
Recommend
GeeksforGeeks
Share
Login
Sort by Newest
checking for case like 999 etc can be avoided if we check in last if(carry>0) thn we have to
increase the size otherwise there is no need for it. Hope It helps :)
Reply Share
pranesh Kumar 2 months ago
http://code.geeksforgeeks.org/...
Reply Share
Ananyo Maiti > pranesh Kumar a month ago
Doesn't work for palindrome numbers like 999 and numbers like 713322 where left
side digit is smaller than right side.
Reply Share
pranesh Kumar 2 months ago
#include<iostream>
#include<string.h>
#include<stdlib.h>
using namespace std;
int main()
{
char a[10];
cin>>a;
int length = strlen(a);
int orginal = atoi(a);
for(int i=0,j=length - 1;i<j;i++,j--) {="" a[j]="a[i];" }="" int="" palidrom="atoi(a);"
if(palidrom=""> orginal)
cout << palidrom << endl;
else
{
int j = 0,k = 1,ag = 1;
while(j < length/2)
{
http://www.geeksforgeeks.org/given-a-number-nd-next-smallest-palindrome-larger-than-this-number/
5/15
05/10/2016
see more
Reply Share
wilson 5 months ago
simple solution
https://ideone.com/QelC7L
Reply Share
Rahul Joshi > wilson 2 months ago
wrong answer for 849987 and for numbers with all 9s like '999999'.
Reply Share
Soham Chakravarty 7 months ago
Reply Share
Debashis Kumar Das 7 months ago
Reply Share
atul 9 months ago
http://ideone.com/4mkGvT
Reply Share
Sahil a year ago
I have done it with a more simple and recursive approach. Check my solution
http://ideone.com/ZTB9ds
Reply Share
Shubham Aggarwal a year ago
http://www.geeksforgeeks.org/given-a-number-nd-next-smallest-palindrome-larger-than-this-number/
6/15
05/10/2016
Any suggestions guys whats wrong with this code ? grtting wrong ans
#include<stdio.h>
int palindrome(long int n)
{
long int t,rev=0;
t=n;
while(t)
{
rev=rev*10;
rev=rev+t%10;
t=t/10;
see more
Reply Share
Dman a year ago
Reply Share
deeksha garg a year ago
plzz can anyone tell what is wrong in this code.... it is giving write answer on ideone but
spoj is showing wrong answer
#include <stdio.h>
int main(void) {
int t,r,c;
long k,n,no;
scanf("%d",&t);
while(t--)
{
scanf("%ld",&k);
if(k<=1000000)
{
c=0;
while(c==0)
{
++k;
n=k;
see more
Reply Share
http://www.geeksforgeeks.org/given-a-number-nd-next-smallest-palindrome-larger-than-this-number/
7/15
05/10/2016
Reply Share
Can anyone plzz tell my mistake in this program... I have being trying it for 3 days
still its showing wrong ans on spoj
Reply Share
Manraj Singh > deeksha garg a year ago
Hey! The question says there are nearly 1000000 digits as input! And that
won't t in long int. Use a string.
Reply Share
deeksha garg > Manraj Singh a year ago
But how can I use string in c... I have to take an char array in it and it
will increase the memory... Can u plzz help
Reply Share
Manraj Singh > deeksha garg a year ago
Yes it will increase memory but you have more than enough memory
to use. http://ideone.com/LWzgW7
Reply Share
deeksha garg > Manraj Singh a year ago
Reply Share
Manraj Singh > deeksha garg a year ago
Reply Share
Markandayan P a year ago
Reply Share
8/15
05/10/2016
{ found=0;
scanf("%d",&num);
while(found==0)
{ i=0;
see more
Reply Share
Md Farooq 2 years ago
awesome explanation
Reply Share
manas 2 years ago
Reply Share
Uma Kanth > manas a year ago
This does not work for numbers greater than the int range. Consider a test case
with input more than 1000000 digits.
Reply Share
Aman Mittal 2 years ago
9/15
05/10/2016
number = number + 1;
String string = Integer.toString(number);
int num[] = new int[string.length()];
for (int i = 0; i < string.length(); i++) {
num[i] = string.charAt(i);
num[i]-=48;
}
int check = 0;
if (num.length > 2) {
if (num.length % 2 != 0) {
for (int i = 0; i <= (num.length / 2) + 1; i++) {
see more
Reply Share
Rohin Mehra 2 years ago
Reply Share
Kenneth 2 years ago
Here is my iterative solution and tests, where the input is an integer number, rather than a
digit array. The time complexity is O(d) and space complexity is O(1), where d is the digit
count of the input integer.
http://ideone.com/1ntnAa
3
Reply Share
@geeksforgeeks
Please nd below recursive approach for nd the next smallest palindrome"
Algorithm :If number is all 9's say 99 then then its palindrome will be 101. For 999 answer is 1001 and
so on
For other cases
if input is 1356 then we will start with rst & digit same as input 1 _ _ 1
Now we will call same function to get palindrome of internal number by striping rst and
last digit viz. 35.
So function call for 35 will return 44
So answer for 1356 is 1 4 4 1
Now if number is 1996 the we will start with 1 _ _ 1
Now we will call same function to get palindrome of internal number by striping rst and
last digit viz. 99.
So function call for 99 will return 101
So it returned palindrome of length more than 2; it means we should increase outer digit to
make it 2 _ _ 2
And we should ll it up with zeros.
http://www.geeksforgeeks.org/given-a-number-nd-next-smallest-palindrome-larger-than-this-number/
10/15
05/10/2016
Reply Share
Soumik Chatterjee > kaushik Lele 2 years ago
Your algorithm won't work for numbers such as 7992.It will give 8008, whereas
7997 should be the answer.
2
Reply Share
Aneek Roy > Soumik Chatterjee a year ago
bhai _/_
Reply Share
kaushik Lele > Soumik Chatterjee 2 years ago
Reply Share
Sahil > kaushik Lele a year ago
You missed few cases. I have used a similar approach which cover
all the cases. http://ideone.com/ZTB9ds
Reply Share
Karshit Jaiswal 2 years ago
Very poorly explained approach. By only looking at the approach you cannot code it.
Please explain the 2 sub cases properly with more vivid examples.
Reply Share
kaushik Lele > Karshit Jaiswal 2 years ago
Reply Share
Basant 2 years ago
Reply Share
Ekta Goel > Basant 2 years ago
i and j after comparing the middle digits are 1 and 4, and now a[1]<a[4], hence,=""
increment="" the="" middle="" digit="" i.e.a[2]="" and="" propagate="" the=""
carry="" forward="" and="" simultaneously="" copy="" the="" left="" half="" to=""
its="" right="" half.="" i.e.="" 1(1+1)0="" 921,="" copying="" now="" to="" its=""
right="" half="" we="" get="" 120021="" as="" the="" next="" palindrome.="">
Reply Share
Guest > Basant 2 years ago
i and j after comparing the middle digits are 1 and 4, and now a[1]<a[4], hence,=""
increment="" the="" middle="" digit="" i.e.a[2]="" and="" propagate="" the=""
http://www.geeksforgeeks.org/given-a-number-nd-next-smallest-palindrome-larger-than-this-number/
11/15
05/10/2016
Reply Share
Israil Bony 2 years ago
Reply Share
sharath 2 years ago
Reply Share
http://www.geeksforgeeks.org/given-a-number-nd-next-smallest-palindrome-larger-than-this-number/
12/15
05/10/2016
I have O(logn) solution with no lengthy code and testing only three conditions-1.whether it is 1 digit number? -- O(1)
2.whether it contain all 9 or not? -- O(logn)
3.otherwise. -- O(logn)
here is code-#include<stdio.h>
void print(int arr[], int u)
{
int i;
printf("Next smallest palindrome is :n");
for(i=0;i<u;i++) {="" printf("%d="" ",arr[i]);="" }="" printf("n");="" }="" void=""
see more
Reply Share
Saurabh > typing.. 2 years ago
Reply Share
typing.. > Saurabh 2 years ago
Reply Share
kinshuk chandra 2 years ago
Reply Share
sammyblr 2 years ago
http://www.geeksforgeeks.org/given-a-number-nd-next-smallest-palindrome-larger-than-this-number/
13/15
05/10/2016
Reply Share
rahul 3 years ago
@GEEKSforGeeks
We can have one check before the code mirror left to right
i.e.
if(!leftsmaller)
mirror left to right;
else
increment middle case
This would save lot of time for the cases in which we are increment middle digit as for this
copying left to right is an unnecessary steps.
thnx
2
Reply Share
Reply Share
Rahul > Preeti 3 years ago
No its 9 4 1 8 8 0 8 8 1 4 9
1
Reply Share
http://www.codechef.com/viewso...
Reply Share
Akash Verma 3 years ago
Reply Share
Sri Hari > Akash Verma 3 years ago
Yeah totally!!
Not the execution time complexity but the implementation time complexity.
6
Reply Share
Load more comments
Privacy
http://www.geeksforgeeks.org/given-a-number-nd-next-smallest-palindrome-larger-than-this-number/
14/15
05/10/2016
@geeksforgeeks, Some rights reserved Contact Us! About Us! Advertise with us!
http://www.geeksforgeeks.org/given-a-number-nd-next-smallest-palindrome-larger-than-this-number/
15/15