今天想到了一个比较有意思的for循环题:0,1,1,2,2可以组成多少个不重复的五位数?
它主要是for循环多层嵌套外加if判断,代码如下:
protected void Button1_Click(object sender, EventArgs e) { List<string> list = new List<string>(); string[] ss = { "0","1","1","2","2" }; string str = ""; //万位 for (int i = 1; i < 5; i++) { //千位 for (int k = 0; k < 5; k++) { if (i != k) { //百位 for (int m = 0; m < 5; m++) { if (i != m & k != m) { //十位 for (int n = 0; n < 5; n++) { if (i != n & k != n & m != n) { //个位 for (int x = 0; x < 5; x++) { if (i != x & k != x & m != x & n != x) { str = ss[i] + ss[k] + ss[m] + ss[n] + ss[x]; //判断是否重复 bool b = true; for (int y = 0; y < list.Count; y++) { if (str == list[y]) { b = false; } } if (b == true) { list.Add(str); } } } } } } } } } } Label2.Text = "结果是:" + list.Count.ToString(); }