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;
}
}
}
Question
han84
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.
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