面试会遇到的几个小程序:
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(); }
|
请发表评论