• 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

    • The 2025 Complete Splunk Beginner Bundle is now 25% off by Steven Parker Today's highlighted deal comes via Neowin Deals store, where you can save 75% on The 2025 Complete Splunk Beginner Bundle. Splunk is a powerful data platform used to gather information from multiple sources and index it for efficient access. You can then use collected data to create visualizations, analytics, and a variety of automated and security-related functions. With its web-style interface, Splunk is easy to use and is utilized by many companies worldwide. What's Included: Splunk Fundamentals for Effective Management of SOC and SIEM Oak Academy 38 Lessons (3.5h) Lifetime $20.00 Value Splunk | Splunk Core Certified User Certification Prep Lab Oak Academy, 63 Lessons (6h),Lifetime, $20.00 Value Splunk | Splunk Core Certified Power User SPLK 1002 Prep Oak Academy, 53 Lessons (5.5h), Lifetime, $20.00 Value Splunk| Splunk Enterprise Certified Admin Certification Prep Oak Academy, 68 Lessons (8.5h), Lifetime, $20.00 Value Requirements Basic understanding of IT and networking concepts Familiarity with Linux and Windows operating systems A computer with internet access for hands-on practice Good to Know Length of time users can access this course: lifetime Access options: desktop or mobile Redemption deadline: redeem your code within 30 days of purchase Experience level required: all levels Certificate of Completion ONLY Updates included Closed captioning NOT available NOT downloadable for offline viewing Learn more about our Lifetime deals here! Lifetime access to this 2025 Complete Splunk Beginner Bundle normally costs $80, but this deal can be yours for just $19.99, that's a saving of $60. For full terms, specifications, and info, click the link below. Get the 2025 Complete Splunk Beginner Bundle for just $19.99 (75% off MSRP: $80) Although priced in U.S. dollars, this deal is available for digital purchase worldwide. We post these because we earn commission on each sale so as not to rely solely on advertising, which many of our readers block. It all helps toward paying staff reporters, servers and hosting costs. Other ways to support Neowin Whitelist Neowin by not blocking our ads Create a free member account to see fewer ads Make a donation to support our day to day running costs Subscribe to Neowin - for $14 a year, or $28 a year for an ad-free experience Disclosure: Neowin benefits from revenue of each sale made through our branded deals site powered by StackCommerce.
    • and you got scammed because 2077 launch its one of the worse thing i ever remember and even to this day the game never reached its potential
    • Basic Auth needs to die especially for anything internet bound and exchange in the office 365 suite is extremely internet bound as the cloud service it is. Microsoft has been announcing it for years now. There is always a balance between security and usability, in this case it should be glaringly obvious.
    • the more they want to charge more the more people won't buy anything at launch and wait until its reduced price or discount, hell i even waited until its free on epic game store. and smoke pass model its not viable and having others to pay 80 dollars to subside it wont help
    • Pandemic of 2020, AKA justification to "print" 10 trillion $$$ and keep the Ponzi scheme alive for another while. Until the next one.
  • Recent Achievements

    • Apprentice
      Wireless wookie went up a rank
      Apprentice
    • Week One Done
      bukro earned a badge
      Week One Done
    • One Year In
      Wulle earned a badge
      One Year In
    • One Month Later
      Wulle earned a badge
      One Month Later
    • One Month Later
      Simmo3D earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      558
    2. 2
      ATLien_0
      258
    3. 3
      +FloatingFatMan
      182
    4. 4
      Michael Scrip
      124
    5. 5
      Steven P.
      100
  • Tell a friend

    Love Neowin? Tell a friend!