Search code examples
c++integerpalindrome

c++ rearranging an integer


I'm currently a C++ student and I'm on the basics part of C++, so please excuse me if this seems simple for you guys but I find it the hardest problem I ever had: It is given a number n with exactly 8 digits. Find the biggest palindrome number obtained by the rearrangement of all digits of n. Example: 21523531 => 53211235

I know vectors and how to check if a number is palindrome, I also know how to remove each digit from a number until it gives me a palindrome number, but I have no ideea how I can rearrange ALL digits.


Solution

  • I think followng code will work:

    int func(int x) // returns 0 if there is no valid palindrome
    {
        int arr[10]{};
        while (x)
        {
            arr[x%10]++;
            x /= 10;
        }
        for (int it : arr)
            if (it % 2)
                return 0;
        int ret = 0;
        for (int i = 9; i >= 0; i--)
            for (int j = 0; j < arr[i]/2; j++)
                ret = ret * 10 + i;
        for (int i = 0; i < 10; i++)
            for (int j = 0; j < arr[i]/2; j++)
                ret = ret * 10 + i;
        return ret;
    }
    

    And here is more student-readable version:

    int func(int x) // returns 0 if there is no valid palindrome
    {
        int arr[10] = {0,0,0,0,0,0,0,0,0,0}; // it is digits counter
        while (x) // this is executed for each digit in the number
        {
            arr[x%10]++; // here x%10 is equal to current digit
            x /= 10; // remove rightmost digit
        }
        for (int i = 0; i < 10; i++)
        {
            if (arr[i] % 2) // Every digit must be repeated 0,2,4,6 or 8 times. If it's not, then there is no valid palindrome
            {
                return 0;
            }
        }
        int ret = 0; // this is our future result
        // Now we just take largest digit that appears in source number and add it to the result. If it appears twice, we add it once. If it appears 4 times, we add it twice and so on.
        for (int i = 9; i >= 0; i--)
        {
            for (int j = 0; j < arr[i]/2; j++)
            {
                ret = ret * 10 + i;
            }
        }
        // Now we're doing same thing in the reverse direction.
        for (int i = 0; i < 10; i++)
        {
            for (int j = 0; j < arr[i]/2; j++)
            {
                ret = ret * 10 + i;
            }
        }
        return ret; // we're done now
    }
    

    I hope you'll find this answer usefull and will use it without blind copy.