• 0

[C#] Find Nearest Palindrome


Question

Hi All,

I am creating a console application to find the nearest palindrome number to the one submitted, for the life of me I cannot figure out how to make it find the next highest palindrome it will return the same number if that is a palindrome and also will literally do the closest even if it is less.

I would really appreciate any help.

namespace PalidromeC
{
    class Program
    {
        static public void Main(string[] args)
        {
            int palindrome = NearPalindromeFinder.findNearPalindrome(101);
            Console.WriteLine("Nearest Palindrome = " + palindrome);
        }

    }

    public class NearPalindromeFinder
    {
        public static int findNearPalindrome(int start)
        {
            if (testPalindrome(start))
                return start;
            else
            {
                int neg = start;
                int pos = start;
                for (int i = 0; i < start; i++)
                {
                    if (testPalindrome(start + i))
                    {
                        pos = start + i;
                        break;
                    }                                                       
                }
                return (start == neg) ? pos : neg;
            }
        }

        public static string ReverseString(string s)
        {
            char[] arr = s.ToCharArray();
            Array.Reverse(arr);
            return new string(arr);
        }


        private static bool testPalindrome(int start) 
         {
           if (start == 0 || start == 1)
            return true;
           String str = Convert.ToString(start);
           String rev = ReverseString(str);     
           if (str.Equals(rev))
             return true;
           else
             return false;
         }

    }


}	

Link to comment
https://www.neowin.net/forum/topic/884304-c-find-nearest-palindrome/
Share on other sites

7 answers to this question

Recommended Posts

  • 0
  On 17/03/2010 at 12:27, njlouch said:

Quite clearly stated:

I am creating a console application to find the nearest palindrome number to the one submitted

Quite clearly:

An example serves to clarify objectively a textual description

han84, you don't really need ReverseString if you are using C#. Is there no in-built function for this? Also, why don't you look at code where you copied it from: http://stackoverflow.com/questions/2455411/find-the-closest-palindrome-number-c . It might give you some ideas.

  • 0
  On 17/03/2010 at 12:37, Jebadiah said:

Quite clearly:

An example serves to clarify objectively a textual description

han84, you don't really need ReverseString if you are using C#. Is there no in-built function for this? Also, why don't you look at code where you copied it from: http://stackoverflow.com/questions/2455411/find-the-closest-palindrome-number-c . It might give you some ideas.

The code that you quoted is mine, I also asked for help on that site, still had no luck with any answers. I have no idea if there is an in-built function, I'm only a beginner and at the moment am unsure of how to re-work this code so that it ignores if you start on a palindrome number.

  • 0

The code you pasted in your OP works.

To ignore the first number,

(A) just do start++ when you enter the function findNearPalindrome. Clearly you want to ignore the first number no matter what. start++ increments value in start by 1.

OR

(B) Start your for loop from i=1.

However, you can make this more efficient by using the following method:

If your original number is say 9847, the next palindrome will be 98__ ... 98_9 ... 9889.

If your original number is say 37284, the next palindrome will be 37___ ...37__3 ... 37_73 ... 37373 (not 37273 because you want the next palindrome number).

This method makes it faster. You won't need to use the testPalindrome function. Think about improvements.

Also, please comment your code. It's hard to understand because anyone other than you will have a hard time understanding what "pos", "neg", "start", etc. mean.

  • 0
  On 17/03/2010 at 19:35, Jebadiah said:

The code you pasted in your OP works.

To ignore the first number,

(A) just do start++ when you enter the function findNearPalindrome. Clearly you want to ignore the first number no matter what. start++ increments value in start by 1.

OR

(B) Start your for loop from i=1.

However, you can make this more efficient by using the following method:

If your original number is say 9847, the next palindrome will be 98__ ... 98_9 ... 9889.

If your original number is say 37284, the next palindrome will be 37___ ...37__3 ... 37_73 ... 37373 (not 37273 because you want the next palindrome number).

This method makes it faster. You won't need to use the testPalindrome function. Think about improvements.

Also, please comment your code. It's hard to understand because anyone other than you will have a hard time understanding what "pos", "neg", "start", etc. mean.

Thank you so much that's a massive help, and I will put some comments in. Thanks again!

  • 0
  On 18/03/2010 at 08:42, han84 said:

Thank you so much that's a massive help, and I will put some comments in. Thanks again!

You're welcome. There's an efficient algorithm explained on this page for determining the next palindrome number of a given number. It takes care of various scenarios which my example above doesn't.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • LibreOffice narrows gap with Microsoft Office in 25.8 Beta 1 by David Uzondu The Document Foundation has released LibreOffice 25.8 Beta 1 for public testing on Linux, macOS, and Windows. This is the second pre-release for the 25.8 cycle and the foundation says that the final, stable version of LibreOffice 25.8 is expected to land at the end of August 2025. Starting off with Writer, LibreOffice's Word, the developers have finally addressed some long-standing annoyances, including a new command to easily insert a paragraph break right before a table. This beta also introduces a useful privacy feature in its Auto-Redact tool, letting you strip all images from a document with a single option. To use it, go to Tools and select the Auto-Redact option: The application has improved its ability to handle different languages for punctuation, preventing mix-ups in multilingual documents. Other notable improvements have also been made. A new hyphenation rule lets you choose to prevent a word from splitting at the end of a page, moving the whole line to the next page instead. Microsoft Word has had this feature for years now. The Navigator now displays a handy tooltip with word and character counts for headings and their sub-outlines. Scrolling behavior when selecting text has been improved, making it less erratic. A new command with a keyboard shortcut was added for converting fields into plain text. Calc gets a lot of new functions that bring it closer to its competitors like Excel, including TEXTSPLIT, VSTACK, and WRAPROWS. Impress now properly supports embedded fonts in PPTX files, which should reduce headaches when sharing presentations with PowerPoint users. Alongside these additions, the project is also cleaning house; support for Windows 7, 8, and 8.1 has been completely dropped. There are also smaller UI tweaks across the suite, like allowing a single click to enter rotation mode for objects in Writer and Calc. macOS users get better integration, with proper support for native full screen mode and new window management features from the Sequoia update. In terms of performance, the team has optimized everything from loading huge DOC files and XLSX spreadsheets with tons of conditional formatting to simply switching between sheets in Calc. These improvements should be noticeable, especially when working with complex documents. A new application-wide "Viewer mode" has also been implemented, which opens all files in a read-only state for quick, safe viewing. On a related note, The Document Foundation has joined efforts by the likes of KDE to encourage Windows 10 users to switch to Linux. Also, you might have heard that Denmark, in a bid to lessen its reliance on Microsoft, has decided to make a full switch to LibreOffice, with plans to begin phasing out Office 365 in certain ministries as early as next month. If you're interested in this release, you can read the full release notes and download the binaries for your platform: Windows, macOS (Intel | Apple Silicon), or Linux (DEB | RPM). You can also get the latest stable version from our software stories page.
    • Until it can be used 100% offline (ie: PST file support or equiv) not even considering it. I'll jump to Thunderbird first which has gotten a LOT better since the last time I looked at it.
  • Recent Achievements

    • Explorer
      Case_f went up a rank
      Explorer
    • Conversation Starter
      Jamie Smith earned a badge
      Conversation Starter
    • First Post
      NeoToad777 earned a badge
      First Post
    • Week One Done
      JoeV earned a badge
      Week One Done
    • One Month Later
      VAT Services in UAE earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      548
    2. 2
      ATLien_0
      232
    3. 3
      +FloatingFatMan
      158
    4. 4
      +Edouard
      116
    5. 5
      Michael Scrip
      114
  • Tell a friend

    Love Neowin? Tell a friend!