gpt4 book ai didi

c++ - 冰雹序列 C++ 递归

转载 作者:行者123 更新时间:2023-11-30 03:18:30 25 4
gpt4 key购买 nike

我在将以下代码从使用循环转换为仅使用递归时遇到了一些麻烦。

//longestHailstoneStartValue also cycles through each of the sequences from 1 
//to 'n' and after it is determined what the largest length is, it finds which
//number corresponds with the longest length function.
//
//Sample input: '8'
//Sample output: '7'
//'7' is from the sequence starting with 7.

int longestHailstoneStartValue(int n)
{
int u=1, w=0, z=0;

while(n>=u)
{
if(w<lengthHailstone(u))
{
w=lengthHailstone(u);
z=u;
}

u++;
}

return z;
}

我必须将其转换为递归,并采用任何未使用/存储有新值的额外变量。

最佳答案

你必须取出变量z,因为它实际上没有用,只是存储u的值,这可以增加复制值的内存uz...

此外,请阅读 recursion to know more about what it actually is ...它只是根据自己的定义一次又一次地调用相同的方法...

int longestHailstoneStartValue(int n)
{
int u = 1, w = 0;
if(w < lengthHailstone(u))
w = lengthHailstone(u); // Removed 'z'...
u++;
/* '?' is the ternary operator... If n is greater or equal to u then print the
original value of u (Note the 'u++') or else recursively call the function till
the condition 'n >= u' is satisfied... */
return n >= u ? u - 1 : longestHailstoneStartValue(n); /* 'u - 1' since 'u' will
increment by 1 even when
the given condition is
true... */
}

关于c++ - 冰雹序列 C++ 递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54684230/

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