Maximum number that can be formed from the given digits

前端 未结 2 347
执笔经年
执笔经年 2021-01-16 14:25

Given a Integer, find the maximum number that can be formed from the digits. Input : 8754365 output : 8765543

I told solution in $O(n logn)$. He asked me optimize

2条回答
  •  自闭症患者
    2021-01-16 15:11

    RunTime: 00:00:00.01

    public int Assignment(int number) 
    {
        // Consider that int.MaxValue equals to 2147483647
        var siblingString = String.Join("", number.ToString().ToCharArray().OrderByDescending(n => n));
        int sibling = -1;
        if (!int.TryParse(siblingString, out sibling) || sibling > 100000000)
        {
            return -1;
        }
        return sibling;
    }
    

    Performances tested with the following code:

    static void Main()
    {
        Stopwatch stopWatch = new Stopwatch();
    
        stopWatch.Start();
        var result = AssignmentOne(2147483646);
        stopWatch.Stop();
    
        TimeSpan ts = stopWatch.Elapsed;
        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
        Console.WriteLine("RunTime " + elapsedTime);
    }
    

提交回复
热议问题