Flipkart Interview Question
Software Engineer / DevelopersI assumed that there wont be overflow and the number is palindrome.
Dealing with a number which cant be expressed in 32 or 64 bit of architecture is another area of research and many papers had been already published but in the same question if numbers are represented as string then above algorithm holds with few modifications.
@Tulley I have observed that you have developed a habit of posting wrong solutions on most of the problems posted on the website.. please spend sometime in making sure that your solutions work .. will it work for 99->101
@Anonymous: Thanks for yr valuable suggestion. It always happens that u r not able to identify all bugs in yr code. I love to put code here for discussions, suggestions and taking input from many minds :)
By the way I've edited the above code n hope it works for all the cases now.
@tully i am assuming that in all given solution urs is working fine so could un plz tell me what to do if number is big like 15 digit no. 123456789123456
the how to find next palindrome of it..using int & long its giving error ..?? i mean integer overflow..??
@tully i am assuming that in all given solution urs is working fine so could un plz tell me what to do if number is big like 15 digit no. 123456789123456
the how to find next palindrome of it..using int & long its giving error ..?? i mean integer overflow..??
Hi Algoseekar:
if u have data type (built in or user defined) to take input for big integers then same u can use in my code for processing and output.
if u r taking the input as string of digits then one of the solution given below is extremely good and clean:
ideone.com/ElXqx given by some anonymous.
Spec in Haskell
next :: Int -> Int
next p = palindromes [p+1..] where
palindromes (x:xs) =
let str = show x in
if str == reverse str then x else palindromes xs
#include<stdio.h>
#include<conio.h>
int main()
{
int n;
int u,l,num,count1=0,b,count2=0;
int a=1;
int sum=0;
int sum2=0;
scanf("%d",&n);
num=n;
while(a<n)
{
a=a*10;
++count1;
}
a=a/10;
if(count1%2==0)
{
u=1;
}
else
{
u=2;
}
b=a;
while(num!=0)// loop to add 11 to the middle 2 for even and 1 for odd.
{
if((u==1)&&((count2==(count1/2-1))||(count2==count1/2)))
{
sum=sum+b;
sum2=sum2+(num/b)*b;
printf("\n%d",sum);
if(count2==count1/2)
{break;}
}
if((u==2)&&(count2==count1/2))
{
sum=sum+b;sum2=sum2+(num/b)*b;printf("\n%d",sum);break;
}
num=num%b;
b=b/10;
++count2;
}
if(sum2%9==0)// cheking the case of 999 0r 9999
{
n=n+2;
}
else
{
n=n+sum;
}
printf("next palindrome is: %d",n);
getchar();
getchar();
return 0;
}
The code is not proper ly formatted, but works well try 2 understand it. Plz post any problem in it.
The concept is if the number of digits is even : add 11 to the middle 2 numbers
" "odd : add 1 " " number
Check foe if the addition does not cause any change in the number of digits for example:
999 + 010 = 1000 not a palindrome the ans should be 1001.
check my solution here ideone.com/ElXqx
tested input cases:
0 -> 1
9 -> 11
999 -> 1001
9999 -> 10001
10001 -> 10101
100001 -> 101101
52960 -> 53035
4998 -> 5005
+1 comprehensive and neat solution seems to be 100% correct, unlike the 90% of the users on CC who post ad-hoc idea/code only.
@lshmouse: I think you probably need to understand the problem first before looking at input/output case. Question is asked for NEXT LARGEST palindrome, NOT NEAREST palindrome. Hence, 53035 is NEXT LARGEST palindrome of 52960, and 5005 is NEXT LARGEST palindrome of 4994. An advice for you, if you DON'T understand a question, first ask others to clarify that. No offense.
@Verma: palindrome is never considered as +ve/-ve numbers. I doubt where from you got this information.
Of course, if you need to get NEXT SMALLEST palindrome, you can easily tweak my idea to get the NEXT SMALLEST. Try it as an exercise to show your understanding. Thanks.
@Anonymous
y next smallest?
if -101 is a palindrome integer then according to the question next largest palindrome integer is -99.
Have a look on this "acmicpc-live-archive.uva.es/nuevoportal/data/p2552.pdf". It talks about negative palindrome integres. Hope u'll correct your code.
How about this?.
int nextPalindromInt(int inPalindromeInt)
{
int numOfDigits = 0, halfDigits=0, secondHalf=0, firstHalf = 0;
if ((inPalindromeInt >= -9) && (inPalindromeInt <= 9))
return inPalindromeInt;
/*Get Total number of digit */
numOfDigits = (int)(Math.Log10(inPalindromeInt) / Math.Log10(10) + 1);
halfDigits = numOfDigits / 2;
firstHalf = (int)(inPalindromeInt / Math.Pow(10,(numOfDigits/2))) + 1;
if (inPalindromeInt % 9==0 && halfDigits >1)
secondHalf = firstHalf / 100;
else if((inPalindromeInt % 9==0 && halfDigits ==1) || (numOfDigits % 2 == 1))
secondHalf = firstHalf/10;
else if (numOfDigits % 2 == 0)
secondHalf = firstHalf;
firstHalf = (firstHalf * (int)Math.Pow(10, halfDigits));
while (secondHalf > 0)
{
firstHalf += (int)((secondHalf % 10) * (int)Math.Pow(10, halfDigits - 1));
halfDigits--;
secondHalf /= 10;
}
return firstHalf;
}
Flip all de 9s starting from de middle on both sides to 0.increment de first non 9 on both sides...u may need to add trailing or leading zeros
Does your solution say ANYTHING about a REAL solution?
Freaking stupid, why you post same message twice :-O
@LOL: my browser refreshed twice while posting...i m sure u dont understand ANYTHING of wat i m saying lets see if some illustration can help you
12344321->start from middle, no 9s, increment 1st non-9 ie both 4's 12355321 is the next palin
123999321->next palin->124000421
129921->130031
string of all 9's is a corner case and u should output 1 less 0 9->11,99->101 etc
class nextPalindrome{
public static void main(String[] args){
System.out.println(findNextPalindrome(222));
}
public static int findNextPalindrome(int num){
if(num+1 == (int)Math.pow(10,(int)Math.log10(num+1)))
return num+2;
int numDigits = (int)Math.log10(num) + 1 ;
int firstHalf = num/(int)Math.pow(10,numDigits/2);
firstHalf +=1;
String str = (new Integer(firstHalf)).toString();
if(numDigits%2 == 0){
str = str + new StringBuffer(str).reverse();
}
else{
str = str + new StringBuffer(str.substring(0,str.length()-1)).reverse();
}
int result = Integer.parseInt(str);
return result;
}
}
/*Given a palindrome find an algorithm to get the next palindrome*/
int getNextBigPalindrome(int palin){
String palinString = new String(palin);
int numDigits = palinString.length();
//abcdefgh = 8 ==> abc
//abcd i efgh = 9 ==> abcd
String leftPart = numDigits%2 == 0 ? palinString.subString(0, numberDigits/2-1):
palinString.subString(0, numberDigits/2);
//abcdefgh = 8 ==> de
//abcd i efgh = 9 ==>i
String centerPart = numDigits%2 == 0 ? palinString.subString(numberDigits/2-1,
numberDigits/2+1):
palinString.subString(numberDigits/2,
numberDigits/2+1);
//abcdefgh = 8 ==> fgh
//abcd i efgh = 9 ==> efgh
String rightPart = numDigits%2 == 0 ? palinString.subString(numberDigits/2+1,numDigits):
palinString.subString(numberDigits/2+1, numDigits);
int leftInt = String.parseInt(leftPart);
int centerInt = String.parseInt(centerPart);
int rightInt = String.parseInt(rightPart);
if(centerPart.length == 1){
if(centerInt != 9){
//Case of 111, 121, 131, 141, 151, 161, 171, 181
centerInt += 1;
centerPart = new String(centerInt);
}else{
//Case of 191
centerPart = "0";
leftInt++;
leftPart = new String(leftInt);
rightPart = leftPart.reverse();
}
}else{
if(centerInt != 99){
//Case of 1111, 1221, 1331, 1441, 1551, 1661, 1771, 1881
centerInt +=11;
centerPart = new String(centerInt);
}else{
//Case of 1991
centerPart = "00";
leftInt++;
leftPart = new String(leftInt);
rightPart = leftPart.reverse();
}
}
return String.parseInt(leftPart + centerPart + rightPart);
}
<pre lang="" line="1" title="CodeMonkey18529" class="run-this">/*
For odd no of digits, icrement the left half (including middle element) and reverse the no (leaving the rightmost) and add it to the incremented no
For even no of digits, simply take left half, increment it by one, reverse the incremented no and add it to the right
*/
public static Integer nextLargestPalindrome(Integer no){
String s = no.toString();
int len = s.length();
if(len % 2 == 1){
String left = s.substring(0,len/2 + 1);
int x = Integer.parseInt(left)+1;
return Integer.parseInt(x+reverse(x/10));
}
else{
String left = s.substring(0,len/2);
int x = Integer.parseInt(left)+1;
return Integer.parseInt(x+reverse(x));
}
}
public static String reverse(Integer x){
return (new StringBuffer(x.toString())).reverse().toString();
}
</pre>
The algorithm for the above problem is :
(1) Take the number in form of string eg: 86123,41923
(2) Now take the first half of the string // reverse it and copy to generate a palindrome number eg: 8624--> 8668 86123--> 86168 41923 ---> 41914 4295-->4224
(3) When the generated number is larger than your current number it is the next palindrome.
(4) In case if it is not larger than the current number then add 1 to the middle digit eg: since 4224 is smaller than the original 4295 we add digit 1 and copy the first half of the string after reversing . So 4224 ---> 4334 which happens to be the next palindrome.
There are cases like when generated 41914 is smaller than 41923 then we add 1 and it converts to 41014. In these cases we have to carry 1 to the other half and then reverse + copy. So 41914 --> 42024. Similarly 999 ---> (100)9 --> copy the first half // reverse and paste --> 1001
You may have to take special care of single digit cases like 9 --> 10 --> 11
#include<stdio.h>
#include<conio.h>
unsigned int nextPalin(unsigned int num){
int flag=1,a[10],dig=0,mid,offset=0;
unsigned int cnum;
cnum=num;
while(cnum!=0){
a[dig]=cnum%10;
cnum=cnum/10;
dig++;
if(a[dig-1]!=9){
flag=0;
break;
}
}
if(flag){
return num+2;
}
else{
while(cnum!=0){
a[dig]=cnum%10;
cnum=cnum/10;
dig++;
}
mid=dig/2;
mid--;
if(a[mid]!=a[mid+1]){
if(a[mid+1]==9)
{
a[mid]++;
a[mid+1]=0;
a[mid+2]++;
}
else{
a[mid+1]++;}
}
else{
while(a[mid-offset]==9){
a[mid-offset]=0;
a[mid-offset+1]=0;
offset++;
}
a[mid-offset]++;
a[mid+offset+1]++;
}
int prod=1;
for(int i=0;i<dig;i++){
cnum=cnum+a[i]*prod;
prod*=10;
}
}
return cnum;
}
int main(){
unsigned int num;
printf("Enter the number\n");
scanf("%d",&num);
num=nextPalin(num);
printf("The next palindrome is: %d",num);
getch();
return 0;
}
Case I: The given number is a palindrome..eg: 1234321 then simply increment the center digit by 1 i.e the ans is 1235321
Case II: The given number is not a palindrome:
Subcase 1: The number to the left of the middle digit is greater than the number on the right eg:2194135 (here 219 > 135) then,reverse the left side numbers and replace the right side numbers with them, therefore the ans will be 2194912.
Subcase 2:The number to the right of the middle digit is greater than the number on the left eg:1354219 then,
then increment the middle digit by 1 and then reverse the left side numbers and replace the right side numbers with them. Therefore the answer would be 135 5(middle digit incremented) 531(reversed), resulting in 1355531, which is the next palindrome.
Note: in case the middle digit is 9 then incrementing it would make it 10, so put 0 instead of 9 and increment the first right and left neighboring digit of 9 by 1.
Case1: odd number of digits
case1a: if middle digit is not 9 then increment the middle dight by 1.
case 1b: if middle digit is 9, make it 0 and add 1 to left substring of number, reverse and append it as right substring of number.
case 2: even number of digits
Add 1 to left substring of number, reverse and append it to get next palindrome.
1. Get the num till half of the number of digit of given num.
2. Add 1 in to it.
3. Reverse the num obtained in step 2.
4. Append the numbers obtained in 2 and 3.
***Take care of odd and even num of digits.
- Tulley April 09, 2011