121. A number sequence

JavaScript
Is this helpful ?

medium  - accepted / - tried

Here is a sequence:

  1. '1', first number is 1
  2. '11', since previous number has One(1) 1
  3. '21', since previous number has Two(2) 1s
  4. '1211', since previous number has One(1) 2 and One(1) 1
  5. '111221', since previous number has One(1) 1, One(1) 2, Two(2) 1s
  6. '312211', since previous number has Three(3) 1s, Two(2) 2s, One(1) 1
  7. ....

As explained above, the sequence is generated by counting the digits of previous number.

Please create getNthNum(n) to return the n-th number string in the sequence, n starts from 1.

Let's try to solve this problem within 10 mintues.

Discuss(27)