欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#用遞歸算法實現(xiàn):一列數(shù)的規(guī)則如下: 1、1、2、3、5、8、13、21、34,求第30位數(shù)是多少

 更新時間:2016年06月16日 09:29:44   作者:Robin  
本文主要介紹三種方法,解決面試中常見的問題,求第30位數(shù)是多少的問題,希望能給大家一個參考。

方法一:遞歸算法

/// <summary>
/// 一列數(shù)的規(guī)則如下: 1、1、2、3、5、8、13、21、34求第30位數(shù)是多少, 用遞歸算法實現(xiàn)。(C#語言)
/// </summary>
/// <param name="pos"></param>
/// <returns></returns>
public int GetNumberAtPos(int pos)
{
  if(pos==0||pos==1)
  {
    return 1;
  }
  int res = GetNumberAtPos(pos - 1) + GetNumberAtPos(pos - 2);
  return res;
}

方法二:不用遞歸

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace Test
{
  public class Class1
  {
    private ArrayList list = new ArrayList();

    public Class1()
    {
    }

    public Class1(int num)
      : base()
    {
      int i;

      for (i = 1; i <= num; i++)
      {
        list.Add(Calculation(i));
      }
    }

    private int Calculation(int num)
    {
      if (num == 1 || num == 2)
        return 1;
      else
        return Convert.ToInt32(list[num - 2]) + Convert.ToInt32(list[num - 3]);
    }

    public int Calculation()
    {
      return Convert.ToInt32(list[list.Count - 1]);
    }
  }

  public class test
  {
    public static void Main()
    {
      int j;
      int num;
      for (j = 1; j < 100; j++)
      {
        Console.WriteLine("你要計算第多少位:");
        string readstr;
        readstr = Console.ReadLine();
        if (!string.IsNullOrEmpty(readstr))
        {
          if (int.TryParse(readstr, out num))
          {
            if (num < 1)
              continue;
            else
            {
              Class1 c1 = new Class1(num);
              Console.WriteLine(c1.Calculation());
            }
          }
          else
          {
            continue;
          }
        }
        else
        {
          break;
        }
      }
    }
  }
}

方法三:用循環(huán)實現(xiàn)

public long getNumber(int pos)
{
  long one = 1;
  long two = 1;
  if (pos == 0 || pos == 1)
  {
    return 1;
  }
  int i = 3;
  long sum = 1;
  while (i <= pos)
  {
    sum = one + two;
    one = two;
    two = sum;
    i++;
  }
  return sum;
}

以上就是本文的全部內(nèi)容,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

最新評論