我需要解决一个测试问题,该问题要求计算以X苹果为起始量,Y每次吃苹果,每次吃苹果时添加苹果时总共可以吃多少个苹果1。
我当前的解决方案使用递归函数,因此如果Y小于X或给定X太大,则会导致无限循环。
public class Apples
{
// Counts iterations. If we eat less than we add new every, it'll loop infinetely!
private static int _recursions;
private static int _applesRemaining;
private static int _applesEaten;
public static int CountApples(int startingAmount, int newEvery)
{
if (newEvery > startingAmount) newEvery = startingAmount;
Console.WriteLine("startingAmount: " + startingAmount + ", newEvery: " + newEvery);
_applesRemaining = startingAmount;
/* Eat 'newEvery' amount */
_applesRemaining -= newEvery;
_applesEaten += newEvery;
Console.WriteLine("Eat: " + newEvery + ", remaining: " + _applesRemaining);
/* Get one additional candy */
_applesRemaining += 1;
Console.WriteLine("Added 1.");
if (_applesRemaining > 1 && _recursions++ < 1000)
{
CountApples(_applesRemaining, newEvery);
}
else
{
if (_recursions > 1000) Console.WriteLine("ABORTED!");
/* Eat the one we've just added last. */
_applesEaten += 1;
}
return _applesEaten;
}
public static void Main(string[] args)
{
Console.WriteLine(CountApples(10, 2) + "\n");
}
}
我怎样才能使这更有效?可能有一种更优雅的方法可以做到这一点,但我无法弄清楚。
编辑:原始测试问题文本:
/**
* You are given startingAmount of Apples. Whenever you eat a certain number of
* apples (newEvery), you get an additional apple.
*
* What is the maximum number of apples you can eat?
*
* For example, if startingAmount equals 3 and newEvery equals 2, you can eat 5 apples in total:
*
* Eat 2. Get 1. Remaining 2.
* Eat 2. Get 1. Remaining 1.
* Eat 1.
*/
aluckdog
相关分类