C# - iterative - simple math solution


  • 0

    start with 1 and each iteration try to append a zero. When you can't append a zero look to increment the rightmost number that can be, i.e. it is not a 9, while doing so drop off any 9's on the tail.

        public IList<int> LexicalOrder(int n) 
        {
            IList<int> nums = new List<int>(n);
            int x = 1;
            while (nums.Count < n)
            {
                nums.Add(x);
                if (x * 10 <= n)
                {
                    x *= 10; // append zero
                }
                else
                {
                    while (x % 10 == 9 || x >= n) x /= 10; // drop off any 9's
                    x += 1;
                }
            }
            return nums;
        }
    

Log in to reply
 

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