• 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

    • Here are the top 5 features people still want in Microsoft Teams by Usama Jawad Microsoft Teams is one of the most popular online communication and collaboration tool out there, especially in enterprise environments. Although it receives new features fairly regularly, customers are always clamoring for more, which makes sense given the fact that there are lots of usage scenarios that require coverage when you have millions of users. Back in 2022, we listed the top 10 features that people wanted in Microsoft Teams, and the Redmond tech did roll out some of them globally in the past years. Examples of those include the ability to use multi-tenant accounts and delete private messages. Now, it's time to revisit the same topic in a similar fashion with a list of the top five requests. It is important to note that these feature requests highlighted below are based on the dedicated Feedback portal, are ranked by upvotes, and only include those which have not yet been fulfilled by Microsoft: Enable us to move channels from one team to another (39,451 upvotes): This is similar to what was being requested back in 2022, but Microsoft is still ideating on how to implement this functionality. The item is still in the backlog and the scope and design of the solution are yet to be figured out, and the company is asking for further feedback and ideas in this area. Include Office 365 group calendar (26,998 upvotes): Again a request carrying on from our previous coverage. At that time, Microsoft said that this feature is a priority for it and users will see incremental updates soon. However, the enhancement has now been deprioritized and has been entered in the consideration phase again. The effort to implement this solution would require cross-functional collaboration which doesn't seem to be possible right now, but Microsoft hasn't updated its response in two years. Allow export of Teams chat history (13,685 upvotes): A similar request is present in our previous coverage, but Microsoft says that the ask is still under review, despite vehement support. Enable conversations to move to different channels (13,540 upvotes): In our 2022 coverage, Microsoft suggested workarounds to implement this behavior and its response is almost the same right now. The company is still asking for feedback about why you would want this feature, and people aren't too happy with Microsoft's pace on the issue. Enable access to email from left tab panel (12,265 upvotes): Interestingly, Microsoft has flat out declined this request after internal consideration. That's all for now. It is great to see that many items from our 2022 have been completed and rolled out to customers but the feature requests in this list do indicate that Microsoft sometimes takes years to implement Teams functionality even when the demand is seemingly high. In fact, it can even decline highly-upvoted customer requests without providing detailed justification. What feature do you think is still missing in Microsoft Teams? Let us know in the comments section below and let Redmond know your thoughts in the Feedback portal here!
    • only the copilot pc version went rtm in june. I think rtm was in september, so probably 2 months away.
    • 26200 25H2 is shaping up to be a very solid and stable release, hardly any issues with it here on 3 different configurations of computers
    • Samsung Galaxy S25+ 512GB is $220 off for powerful AI and a pro-grade camera by Paul Hill Are you in the market for a premium Samsung phone? If so, check out the Samsung Galaxy S25+ with 512GB of storage. It’s on Amazon right now for just $899, down 20% from its $1,199.99 list price, representing a significant $220.99 saving. This unlocked device is marked as the number 1 new release by Amazon in the Cell Phones category. If you’re interested, act fast as it’s a limited-time deal. The Galaxy S25+ comes packed with AI features under the umbrella of Galaxy AI. Capabilities include Multiple Tasks with One Ask which brings Google Gemini integration for multi-app commands, Now Brief which proactively gives you information you need to start the day, Audio Eraser to remove distracting sounds from your videos, and advanced portrait features. Powering these features is the Qualcomm SM8750-AB Snapdragon 8 Elite (3 nm) processor which handles all sorts of tasks efficiently including gaming, translation, and photo editing. Alongside the processor is 512GB of storage and 12GB of RAM. The S25+ uses a 6.7-inch QHD+ ProScaler Display which delivers vibrant visuals thanks to its use of Dynamic AMOLED 2X with 3,120 x 1,440 resolution and 120Hz refresh rate. Regarding camera setup, the S25+ has an AI camera with 50MP main sensor, 12MP ultrawide, and 10MP telephoto with OIS. There is also a 12MP front camera. This camera setup is capable of 8K video recording, which is impressive. Finally, you get long battery life with the 4,900 mAh and 45W fast charging support so you don’t need to wait long for it to recharge. If you’re an Android user looking to upgrade to a flagship phone without paying the full price, this deal is for you. If you have an eligible phone to trade in, there is an option to do so to claim up to $725 on the upgrade with Amazon.com Gift Card credit. If you’re excited by AI, but your current phone doesn’t support many AI features, this phone could also be a smart choice. Its display is also great for media consumption, and the processor is robust. Finally, if you have a lot of files to store, the 512GB of storage should be ample. Samsung Galaxy S25+ (Icyblue): $899 (Amazon US) / MSRP $1,199.99 This Amazon deal is US-specific and not available in other regions unless specified. If you don't like it or want to look at more options, check out the Amazon US deals page here. Get Prime (SNAP), Prime Video, Audible Plus or Kindle / Music Unlimited. Free for 30 days. As an Amazon Associate, we earn from qualifying purchases.
  • Recent Achievements

    • Collaborator
      Mighty Pen went up a rank
      Collaborator
    • Week One Done
      emptyother earned a badge
      Week One Done
    • Week One Done
      DarkWun earned a badge
      Week One Done
    • Very Popular
      valkyr09 earned a badge
      Very Popular
    • Week One Done
      suprememobiles earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      566
    2. 2
      +FloatingFatMan
      189
    3. 3
      ATLien_0
      176
    4. 4
      Skyfrog
      112
    5. 5
      Xenon
      110
  • Tell a friend

    Love Neowin? Tell a friend!