Unlucky number 13

前端 未结 6 1013
面向向阳花
面向向阳花 2021-01-18 06:37

I came across this problem Unlucky number 13! recently but could not think of efficient solution this.

Problem statement :

N is taken as input.

6条回答
  •  灰色年华
    2021-01-18 07:25

    I get the feeling that this question is designed with the expectation that you would initially instinctively do it the way you have. However, I believe there's a slightly different approach that would be faster.

    You can produce all the numbers that contain the number 13 yourself, without having to loop through all the numbers in between. For example:

    2 digits: 13

    3 digits position 1: 113 213 313 etc.

    3 digits position 2: 131 132 133 etc.

    Therefore, you don't have to check all the number from 0 to n*9. You simply count all the numbers with 13 in them until the length is larger than N.

    This may not be the fastest solution (in fact I'd be surprised if this couldn't be solved efficiently by using some mathematics trickery) but I believe it will be more efficient than the approach you have currently taken.

提交回复
热议问题