【问题标题】:A recursive algorithm for palindrome testing一种用于回文测试的递归算法
【发布时间】:2015-03-10 15:38:59
【问题描述】:

这是我进行的回文测试的常规方法,但我需要一个递归函数来检查数字是否为回文。

int number, firstnumber, lastnumber, secondnumber, fourthnumber;

readingnumber:

Console.Write("Please enter your palindrome number(5 digits) :" );
//reading the integer number entered
number = Int32.Parse(Console.ReadLine());
//making condition if the number is less than 5 digits
if (number / 100000 != 0)
    goto readingnumber;
else
{
    //we are taking each element alone 
    firstnumber = number / 10000;
    lastnumber = number % 10;
    fourthnumber = (number % 100) / 10;
    secondnumber = (number % 10000) / 1000;

    //making if condition to verify if the number is palindrom or not
    if (firstnumber == lastnumber && secondnumber == fourthnumber)
        Console.WriteLine("\n\nthe number you've enter is palindrom");
    else
        Console.WriteLine("\n\nthe number you've enter is not palindrom");

    //end of program
    Console.WriteLine("\n\n\n\t\tPlease enter any key to exit ...");
}

Console.ReadLine();

【问题讨论】:

  • 当我编辑这个时,我怀疑它是 C#,当我看到 readingNumber: 单独作为一行时,我看到了 goto statement。您可能想阅读类似这样的问题:"What is the best way to avoid goto?"。不惜一切代价避免使用goto - 当肆意使用goto 语句导致难以调试的意大利面条式代码时,就会出现“goto 地狱”之类的东西。

标签: c# recursion palindrome


【解决方案1】:

字符串回文是如果任一

  • 它包含少于 1 个字符
  • Char at[0] == Char at [Length - 1] 和内部字符串 [1..Length - 2] 是回文

所以

public static Boolean IsPalindrom(String value) {
  if (null == value)
    return true; //TODO: or false or throw exception

  if (value.Length <= 1)
    return true;
  else  
    return (value[0] == value[value.Length - 1]) && 
           (IsPalindrom(value.Substring(1, value.Length - 2)));
}

如果您想测试一个数字(例如12321)是否为回文,只需将其转换为string

  int value = 12321;
  Boolean result = IsPalindrom(value.ToString(CultureInfo.InvariantCulture));

【讨论】:

    【解决方案2】:

    一般来说,最好递归地使用Substring,因为您最终会创建大量字符串(实际上,这里所有字符串的内存使用量二次增加 strong> 字符串的长度)。

    String.Intern 的 MSDN 参考说:

    公共语言运行时通过维护一个称为实习池的表来节省字符串存储,该表包含对在程序中以编程方式声明或创建的每个唯一文字字符串的单个引用。因此,具有特定值的文字字符串的实例在系统中只存在一次。

    对于任何给定的字符串,比如"abcdedcba",如果递归地使用Substring,你最终会不必要地将"bcdedcb""cdedc""ded""e"放入实习池。


    相反,最好将相同的字符串传递给递归方法,并改变两个确定要比较的字符的索引。字符串函数很慢,但整数是值类型,可以随意创建和丢弃。


    实施

    /// <summary>
    /// Returns true if the string is a palindrome (an empty string is a palindrome).
    /// Returns false if the string is null or not a palindrome.
    /// </summary>
    public static bool IsPalindrome(string value)
    {
        if ( value == null )
            return false;
    
        if ( value.Length == 0 )
            return true;
    
        return isPalindrome(value, 0, value.Length - 1);
    }
    
    private static bool isPalindrome(string value, int startChar, int endChar)
    {
        if ( value[startChar] != value[endChar] )
            return false;
    
        if ( startChar >= endChar )
            return true;
    
        return isPalindrome(value, startChar + 1, endChar - 1);
    }
    

    用法

    public static void Main()
    {
        var a = IsPalindrome(""); // true
        var b = IsPalindrome("1"); // true
        var c = IsPalindrome("11"); // true
        var d = IsPalindrome("121"); // true
        var e = IsPalindrome("123"); // false
    }
    

    Run it here on ideone.com.

    【讨论】:

      【解决方案3】:

      Run Here

          class Program
              {
                  public static void Main()
                  {
                      var x = 545;
                      var y = 548785445;
                      Console.WriteLine(IsPalindrome(x.ToString()));
                      Console.WriteLine(IsPalindrome(y.ToString()));
                  }
      
                  public static bool IsPalindrome(string text)
                  {
                      if (text.Length <= 1)
                          return true;
                      else
                      {
                          if (text[0] != text[text.Length - 1])
                              return false;
                          else
                              return IsPalindrome(text.Substring(1, text.Length - 2));
                      }
                  }
      
      
              }
      

      【讨论】:

        猜你喜欢
        • 2019-10-25
        • 2021-09-12
        • 2018-05-08
        • 2013-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-17
        相关资源
        最近更新 更多