Using recursion to sum numbers

后端 未结 16 2063
轮回少年
轮回少年 2021-02-05 15:45

I have just been studying the concept of recursion and I thought that I would try a simple example. In the following code, I am attempting to take the numbers: 1, 2, 3, 4, 5, an

16条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-05 16:22

    using System;
    using NUnit.Framework;
    
    namespace Recursion
    {
      [TestFixture()]
        public class Test
        {
            [Test()]
            public void TestSum ()
            {
                Assert.AreEqual (Sum (new int[] { }), 0);
                Assert.AreEqual (Sum (new int[] { 0 }), 0);
                Assert.AreEqual (Sum (new int[] { 1 }), 1);
                Assert.AreEqual (Sum (new int[] { 1, 2, 3, 4, 5 }), 15);
            }
    
            public int Sum(int[] head)
            {
                if (head.Length == 0) return 0;
    
                int[] tail = new int[head.Length - 1];
    
                for (int i = 1; i < head.Length; i++) 
                {
                    tail [i-1] = head [i];
                }
    
                return head[0] + Sum (tail);
            }
        }
    }
    

提交回复
热议问题