C#面试题170420

来源:互联网 发布:数字矩阵切换器包含 编辑:程序博客网 时间:2024/06/14 19:08

1、冒泡排序

int temp;int[] arrSort = new int[] { 10, 8, 3, 5, 6, 7, 9 };for (int i = 0; i < arrSort.Length; i++){for (int j = i + 1; j < arrSort.Length; j++){if (arrSort[j] < arrSort[i]){temp = arrSort[j];arrSort[j] = arrSort[i];arrSort[i] = temp;}}}

2、1  1  2  3  5  8  13  21  34……求第30位数的值?

(1)递归算法

public int GetNumberAtPos(int pos){if(pos==0||pos==1){return 1;}int res = GetNumberAtPos(pos - 1) + GetNumberAtPos(pos - 2);return res;}

(2)不使用递归算法

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;elsereturn 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;}}}}}

(3)用循环实现

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;}

3、传入行数,打印出杨辉三角形

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication1{class Program{static void Main(string[] args){int length = 0;//杨辉三角形的长度 Console.Write("输入杨辉三角长度:"); length = Convert.ToInt32(Console.ReadLine());//指定杨辉三角形的长度int[][] a = new int[length][];//二维数组for (int i = 0; i < a.Length; i++)a[i] = new int[i + 1];//遍历,赋值增量for (int j = 0; j < a.Length; j++){a[j][0] = 1; //把第1列的元素都赋1a[j][j] = 1; //把每1列最右边的元素都赋1for (int m = 1; m < a[j].Length - 1; m++)a[j][m] = a[j - 1][m - 1] + a[j - 1][m];//其余元素的值由杨辉公式计算}for (int i = 0; i < a.Length; i++){  //遍历数组输出杨辉三角形for (int j = 0; j < a[i].Length; j++) Console.Write("{0}\t", a[i][j]);Console.Write("\n");} Console.Read();}}}


0 0
原创粉丝点击