C# 根据提供的数字和符号 输出可能的最大的数值

题目来coding game 的社区puzzle:the greatest number,有0-9,-,. 共12个字符,给你任意的组合(字符可重复),输出最大的数值。

我的代码:

 

using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;

/**
 * Auto-generated code below aims at helping you parse
 * the standard input according to the problem statement.
 **/
class Solution
{
 static void Main(string[] args)
        {
            int N = int.Parse(Console.ReadLine());
            string input = Console.ReadLine().Replace(" ","");
            List<char> inputCharList = new List<char>(input.ToCharArray());
            List<char> outputCharList = new List<char>();

            if(input.Contains("-"))
            {
                outputCharList.Add('-');
                inputCharList.Remove('-');
                if(input.Contains("."))
                {
                    inputCharList.Remove('.');
                    inputCharList.Sort();
                    outputCharList.AddRange(inputCharList);
                    outputCharList.Insert(2,'.');
                }
                else
                {
                    inputCharList.Sort();
                    outputCharList.AddRange(inputCharList);
                }
            }
            else
            {
                if(input.Contains("."))
                {
                    inputCharList.Remove('.');
                    inputCharList.Sort();
                    inputCharList.Reverse();
                    outputCharList.AddRange(inputCharList);
                    outputCharList.Insert(outputCharList.Count-1,'.');      
                }
                else
                {
                    inputCharList.Sort();
                    inputCharList.Reverse();
                    outputCharList.AddRange(inputCharList);
                }
            }
            
            string output = new string(outputCharList.ToArray());
            Console.WriteLine(double.Parse(output));
        }
}

 

 

 

 

 

 

 

目前点赞最高的代码如下:

 

using System;
using System.Linq;

class GreatestNumber
{
    static void Main()
    {
        // Not Used
        var N = Console.ReadLine();
        
        String inputs = String.Concat(Console.ReadLine().Where(x => x != ' '));        
        
        bool hadMinus = inputs.Contains("-"),
             hadDot   = inputs.Contains(".");
        
        String result = hadMinus ? String.Concat(inputs.OrderBy(c => c)) : String.Concat(inputs.OrderByDescending(c => c));   
        
        if(hadDot){
            result = result.Replace(".", "");
            result = result.Insert(hadMinus? 2 : result.Length-1, ".");                
        }
        
        // Trailing/leading 0
        Console.WriteLine(double.Parse(result));
    }
}

 

 

 

 

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页