Clean C# with comments based on Sort


  • 1
    R
    public class Solution {
        public string LargestNumber(int[] nums) {
            Array.Sort(nums, CompareByMagic);
            
            // if first number is 0, that means we have nums[] all 0's, just need to special case this case.
            return nums[0] == 0 ? "0" : string.Join("", nums);
        }
        
        private int CompareByMagic(int a, int b)
        {
            // 1. We need to sort from largest to smallest, hence (b,a) compare to (a, b)
            // 2. If a = 32, b = 7, 732 will be greater than 327, that why we concat the two numbers in string format to make sure
            //    b(7) comes before a(32).
            return (b + "" + a).CompareTo(a + "" + b);
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.