gpt4 book ai didi

c - 使用递归将数字的数字相乘

转载 作者:行者123 更新时间:2023-12-02 06:00:38 30 4
gpt4 key购买 nike

我正在做以下练习:

Given a four digit number such as 3183, compare each digit with the last and if greater or equal multiply it with the following

示例:对于数字3183,它是n = 3*8*3 = 72

我的代码:

#include <stdio.h>

int f ( int n )
{
if ( n < 10 )
return n ;
return (((n/10) % 10) >= (n%10) ? ((n/10)10) : 1) * f((n/100 )* 10 + n % 10 ) ;
}

int main()
{
printf( "%d", f( 3183 );

return(0);
}

有什么方法可以缩短它或使其更好吗?

最佳答案

留下比原来更紧凑的另一种方法:

#include <stdio.h>

int f (int n, int u)
{
if (u > n) return(1);
return (n % 10 >= u ? n % 10 : 1) * f(n/10, u);
}

int main (void)
{
int n = 3284;
printf ("%d", f (n , n%10));

return(0);
}

关于c - 使用递归将数字的数字相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26890577/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com