Python (brute force solution)
f = lambda x: sum( sum( int(k) for k in str(i) ) for i in xrange(1, x+1) )
>>> f(12)
51
>>> f(5)
15
Python (a more elegant solution)
a = lambda x: all(i=='9' for i in x)
l = lambda x: int(x) if a(x) else 10**(len(x) -1 )- 1
s = lambda i: 45*(i*(10**(i-1)))
f = lambda k:s( len(k) - (0 if a(k) else 1 ) ) + f( str(int(k) - l( k )) ) if len( k ) > 1 else sum( xrange(1, int(k)+1) )
>>> f('12')
51
>>> f('5')
15