longle

面试会遇到的几个小程序:

1.有数列如下:1,1,2,3,5,8,13,。。。,请第N位?(请用两种方法得到第N位是多少,并可查询任意一位是多少)

        //斐波那契数
private static List<long> GetNum(long n)
{
long a = 1, b = 1, num = 0;
List
<long> resultArry = new List<long>();
try
{
for (int i = 0; i < n; i++)
{
num
= a + b;
a
= b;
b
= num;
resultArry.Add(num);
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return resultArry;
}

  

static long i = 0, j = 1, result = 0;
static List<long> resultArry = new List<long>();
private static long ReturnNum(long n)
{
if (n <= 2)
{
result
= i + j;
}
else
{
result
= ReturnNum(n - 1) + ReturnNum(n - 2);
}

if (!resultArry.Contains(result))
{
resultArry.Add(result);
}
return result;
}

  

static void Main(string[] args)
{
//方法一:
List<long> resultArry = GetNum(10);
foreach (long result in resultArry)
{
Console.Write(result
+",");
}

//方法二
//ReturnNum(10);
//resultArry.Insert(0, 1);
//foreach (long result in resultArry)
// {
// Console.Write(result+",");
//}

Console.Read();
}

  

分类:

技术点:

相关文章:

  • 2021-07-11
  • 2022-02-26
  • 2021-08-22
  • 2021-10-13
  • 2021-11-19
  • 2021-08-19
  • 2021-11-29
  • 2022-01-16
猜你喜欢
  • 2022-02-27
  • 2021-11-17
  • 2022-01-10
  • 2021-05-30
  • 2021-11-11
相关资源
相似解决方案