1-liners in Python


  • 4

    Based on this, I just didn't want to hide it there and didn't want to clutter that other question more than it already is.

    Using sum with range:

    def countDigitOne(self, n):
      return sum((n/m+8)/10*m + (n/m%10==1)*(n%m+1) for m in (10**i for i in range(10)))
    

    Using recursion, with added default arguments:

    def countDigitOne(self, n, m=1, r=1):
      return int(n>0 and (n+8)/10*m + (n%10==1)*r + self.countDigitOne(n/10, m*10, r+n%10*m))

Log in to reply
 

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