C#面试题170420

31 篇文章 0 订阅
16 篇文章 0 订阅

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

(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列的元素都赋1
				a[j][j] = 1; //把每1列最右边的元素都赋1
				for (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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值