要点:递归的使用,终止条件
有一列数1,1,2,3,5,........求第30个数
public static int Foo(int i) { if (i <= 0) return 0; else if (i > 0 && i <= 2) return 1; else return Foo(i - 1) + Foo(i - 2); }
要点:第二个循环的开始位置
int temp = 0; for (int i = 0; i < arr.Length-1; i++) { for (int j = i; j < arr.Length-1; j++) { if (arr[i] > arr[j+1]) { temp = arr[i]; arr[i] = arr[j + 1]; arr[j + 1] = temp; } } }
要点:递归,终止条件(1x2x..),如果n为2或1那就是本身
public static int Fun(int i) { if (i == 1) { return 1; } if (i == 2) { return 2; } return i * (Fun(i - 1)); }
要点:int[] 数组没有检查的方法,ArrayList有Contains方法
public static void Fun(int len) { int[] arr = new int[len]; ArrayList myList = new ArrayList(); Random rad = new Random(); while (myList.Count < len) { int num = rad.Next(1, len + 1); if (!myList.Contains(num)) { myList.Add(num); } } for (int i = 0; i < len; i++) { arr[i] = (int)myList[i]; } myList.Sort(); Console.WriteLine(myList[len - 1]); }
方法一:算术运算
int a = 10,b = 12; a=b-a; //a=2;b=12 b=b-a; //a=2;b=10 a=b+a; //a=12;b=10
方法二:位运算,通过异或运算也能实现变量的交换
int a = 10, b = 12; //a=1010^b=1100; a = a ^ b; //a=0110^b=1100; b = a ^ b; //a=0110^b=1010; a = a ^ b; //a=1100=12;b=1010;
方式三:变量本身交换数值
b = (a + b) - (a = b);
static void Main(string[] args) { int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 }; int max = arr[0], min = arr[0]; for (int i = 0; i < arr.Length; i++) { if (arr[i] >= max) { max = arr[i]; } if (arr[i] < min) { min = arr[i]; } } Console.WriteLine(string.Format("max{0},min{1}", max, min)); }
static void Main(string[] args) { string str = "abcdcba"; Console.WriteLine(Fun(str)); } private static bool Fun(string str) { for (int i = 0; i < str.Length/2; i++) { if (str[i] != str[str.Length - i - 1]) return false; } return true; }