题解 | 明明的随机数
明明的随机数
https://www.nowcoder.com/practice/3245215fffb84b7b81285493eae92ff0
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
internal static class Class6 {
static public void Main() {
string line = "";
SortedSet<int> ints = new SortedSet<int>();
SortedSet<string> strings = new SortedSet<string>();
while ((line = System.Console.ReadLine()) != null) {
if (line == null) return;
bool isAllDigit = line.All(char.IsDigit);
if (isAllDigit) {
if ( int.TryParse(line, out int num) && num > 0 ) {
for (int i = 0; i < num; i++ ) {
string random = Console.ReadLine();
//输入就有可能是空的,要做判断
if (!string.IsNullOrEmpty(random) && num > 0) {
strings.Add(random);
if (int.TryParse(random, out int num1)) {
ints.Add(num1);
}
}
}
}
}
//Console.WriteLine(" ");
foreach (int n in ints)
Console.WriteLine(n);
}
}
}
In this way,we can use SortedSet<T>,it can automatic sorting the elememnt and dedpublication.We can use two SortedSet,the one is used for save string type element the other for save int type .Every inputs need to be judged whether the input is null or not,as compiler will dig some holes for you in this position.You can use "int.TryParse" to exchange string type to int type and it return bool type.
In the key position,I use a for loop it limited by the one Console.ReadLine()'s input.And then,every lines I save into a string type.Use the if judgement to judge the input is null or not and whether the num is greater than zero or not.In this if range,we can save the string type elements by the SortedSet<srting>,and then I use the other one if to judge the string type whether can be exchanged to int type,if can exchange,add the element into SortedSet<int>.In the last,we should print the result in the last of the while and it can print the result immediately.
The problem has been resloved satisfactorily here.
