Note 1

Take Note:

Take a note while surfing.





Note With Ink

Give your Note a Colorful Tag.




Easy to Access

Stay on same information and in Sync wherever you are.

Note 2

Take Note:

Organize your information,It may take Shape.





Think With Ink

Differ your Content by Color.




Easy to Access

Easy to pull up your content from anywhere anytime.

Note 3

Take Note:

Don't Let information to miss,Because it take shape





Note With Ink

Simple an Easy Way to take a note.




Easy to Access

Get the same in next visit.

Program Discussion :: Strings
Home > Programs > Strings

84. Given a number, find the next smallest palindrome

Answer:

#include <stdio.h>
#include <iostream>
using namespace std;
void printArray (int arr[], int n);
int AreAll9s (int num[], int n );
void generateNextPalindromeUtil (int num[], int n ){
    int mid = n/2;
    bool leftsmaller = false;
    int i = mid - 1;
    int j = (n % 2)? mid + 1 : mid;
    while (i >= 0 && num[i] == num[j])
        i--,j++;
    if ( i < 0 || num[i] < num[j])
        leftsmaller = true;
    while (i >= 0)
    {
        num[j] = num[i];
        j++;
        i--;
    }
    if (leftsmaller == true)
    {
        int carry = 1;
        i = mid - 1;
        if (n%2 == 1)
        {
            num[mid] += carry;
            carry = num[mid] / 10;
            num[mid] %= 10;
            j = mid + 1;
        }
        else
            j = mid;
        while (i >= 0)
        {
            num[i] += carry;
            carry = num[i] / 10;
            num[i] %= 10;
            num[j++] = num[i--]; 
        }
    }
}

void generateNextPalindrome( int num[], int n )
{
    int i;

    cout<< "Next palindrome is:";
    if( AreAll9s( num, n ) )
    {
        cout<< "1 ";
        for( i = 1; i < n; i++ )
            cout<<  "0 " ;
        cout<<  "1" ;
    }

    else
    {
        generateNextPalindromeUtil ( num, n );
        printArray (num, n);
    }
}

int AreAll9s( int* num, int n )
{
    int i;
    for( i = 0; i < n; ++i )
        if( num[i] != 9 )
            return 0;
    return 1;
}

void printArray(int arr[], int n)
{
    int i;
    for (i=0; i < n; i++)
        cout<< arr[i]);
    cout<< "\n";
}

int main()
{
    int num[] = {9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2};

    int n = sizeof (num)/ sizeof(num[0]);

    generateNextPalindrome( num, n );

    return 0;
}

Post Your Answer Here:

Name *
Email

Language:

Post Your Reply Here:



Language:

Post Your Reply Here: