C#用递归计算1-2+3-4+5-6+7-8+9的值,该怎么解决
C#用递归计算1-2+3-4+5-6+7-8+9的值
求大神解决,碰到很多次了。。。
------解决思路----------------------
------解决思路----------------------
求大神解决,碰到很多次了。。。
------解决思路----------------------
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(getValue("1-2+3-4+5-6+7-8+9"));
Console.Read();
}
static int getValue(string p)
{
var index = p.LastIndexOfAny(new[] {'-', '+'});
if (index == -1)
{
return int.Parse(p);
}
return getValue(p.Substring(0, index)) + int.Parse(p.Substring(index));
}
}
}
------解决思路----------------------
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("The value is {0}", Calc(9));
}
static int Calc(int val)
{
if (val == 1) return 1;
return Calc(val - 1) + val * ((val & 1) * 2 - 1);
}
}
}