数字の並び替え
問題
入力した数字を並び替えて最大値と最小値を作りましょう。
入力
・整数を入力する
・整数以外の場合は再入力を求める
出力
・入力値を並び替えた数の最大値と最小値
並び替え
・入力値nに含まれている数を並び替える
・負の数が入力された場合はマイナス記号以外を並び替える
例
例1
値を入力してください >1280 最大値8210 最小値128
例2 負の数の場合
値を入力してください >-8397 最大値-3789 最小値-9873
解答例
using System; namespace NumberSort { class Program { static void Main(string[] args) { int num = ReadNumber(); CNumberSort cns = new CNumberSort(num); Console.WriteLine("最大値{0}", cns.Max); Console.WriteLine("最小値{0}", cns.Min); } static int ReadNumber() { bool loop = true; int n; do { Console.WriteLine("値を入力してください"); loop = !int.TryParse(Console.ReadLine(), out n); } while (loop); return n; } } public class CNumberSort { public int value; public int Max; public int Min; public CNumberSort(int n) { this.value = n; this.Max = 0; this.Min = 0; SetValue(); } public void SetValue(int n) { this.value = n; SetValue(); } private void SetValue() { int[] nums = new int[10]; bool minus = false; String s = string.Empty; String minstr = string.Empty; String maxstr = string.Empty; //数字がマイナスの場合 if (value < 0) { minus = true; s = (-value).ToString(); } else { s = value.ToString(); } //char型配列に変換 char[] carray = s.ToCharArray(); //降順ソート Array.Sort(carray); minstr = new String(carray); //昇順ソート Array.Sort(carray, (x, y) => y - x); maxstr = new String(carray); if (minus == false) { this.Max = int.Parse(maxstr); this.Min = int.Parse(minstr); } else { this.Max = -int.Parse(minstr); this.Min = -int.Parse(maxstr); } } } }