通过递归检查回文[关闭]

问题描述 投票:-1回答:4

我必须检查数字是否是回文或使用递归..我使用以下函数但我很困惑因为每当我使用while循环代替if语句时会生成无限循环!

为什么while循环不能正常工作?

我的代码是:

#include<stdio.h>
int Check_Pal(int);
int main()
{
    int i,sum,n;
    printf("enter no");
    scanf("%d",&n);
    sum=Check_Pal(n);
    if(sum==n)
    {
        printf("palindrome");
    }
    else
    {
        printf("not a palindrome");
    }
    return 0;
}
int Check_Pal(int k)
{
    int r;
    static int sum=0;
    while(k!=0)//if i use an if its fine but while loop does not work 
    {
        r=k%10;
        sum = sum*10+r;
        Check_Pal(k/10);    
    }
    return sum;
}
c recursion palindrome
4个回答
2
投票

您不需要在代码中使用while循环,因为对函数Check_Pal()的递归调用会产生while循环的效果。

考虑下面给出的代码,

while(k!=0)
{
    r=k%10;
    sum = sum*10+r;
    Check_Pal(k/10);    
    ^
    |__ Here you are discarding the value returned by "int Check_Pal()"
}

同样为了获得正确的结果,将变量sum声明为全局可能更好。

尝试这样的事情,

int sum=0;

void Check_Pal(int k)
{
    int r;
    if(k!=0)
    {
        r=k%10;
        sum = sum*10+r;
        Check_Pal(k/10);    
    }
}

int main()
{
  int n;
  printf("enter no");
  scanf("%d",&n);
  Check_Pal(n);
  if(sum==n)
  {
      printf("\npalindrome");
  }
  else
  {
      printf("\nnot a palindrome");
  }
  return 0;
}

1
投票

请参阅,在您的代码中,当您执行Check_Pal(k/10)时,k不会更改,k/10值将在递归调用中分配给k,但不会分配给当前局部变量k。但是你甚至不需要在这里使用while循环。因此,当你在while中给出一个正的非零值表达式时,总是在第一级递归时使用非零k求值为true,因此会出现无限循环。因此,第一次调用中的k永远不会为零......如果给出非零输入

int Check_Pal(int k)
{
    int r;
    static int sum=0;
    while(k!=0)//this always evaluates to true on first level of recursion with non-zero k 
    {
        r=k%10;
        sum = sum*10+r;
        Check_Pal(k/10);//value is assigned to k in recursive call not to the current k
    }
    return sum;
}

祝一切顺利...


1
投票

这是一个使用递归但不需要全局变量的解决方案

bool checkpal(int k) {
    int r = k % 10, power_of_10=1;
    while (10 * power_of_10 < k) power_of_10 *= 10;
    if (k / power_of_10 != r) return false;
    if (power_of_10 == 1) return true;
    int next_k = (k - r * power_of_10) / 10;
    return (power_of_10 == 1000 && next_k < 11 ? next_k == 0 : checkpal(next_k));
}

更新:刚刚意识到这是不完美的。最后一行中的测试power_of_10 == 1000 && next_k < 11只处理一种类型的情况,其中删除最高有效数字导致具有前导零的next_k。毫无疑问,这可以修复,但现在我没有时间。


0
投票

在“while”循环中,您没有更改k,语句“k!= 0”始终为true。因此,你将无限循环。

© www.soinside.com 2019 - 2024. All rights reserved.