Problem:
Score : 500 points

Problem Statement

Find the number of integers between 1 and N (inclusive) that contains exactly K non-zero digits when written in base ten.

Constraints

1 \leq N < 10^{100}

1 \leq K \leq 3

Input

Input is given from Standard Input in the following format:

N
K

Output

Print the count.

Sample Input 1

100
1

Sample Output 1

19

The following 19 integers satisfy the condition:

1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100

Sample Input 2

25
2

Sample Output 2

14

The following 14 integers satisfy the condition:

11,12,13,14,15,16,17,18,19,21,22,23,24,25

Sample Input 3

314159
2

Sample Output 3

937

Sample Input 4

9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999
3

Sample Output 4

117879300

Solution in LuaJIT (2.0.4) (judge verdict: Accepted)

local mfl = math.floor
local ns = io.read()
local k = io.read("*n")
if k == 1 then
  local a = tonumber(ns:sub(1, 1))
  print(a + 9 * (#ns - 1))
elseif k == 2 then
  if #ns == 1 or ns == "10" then print(0)
  else
    local a = tonumber(ns:sub(1, 1))
    local b, bpos = 0, #ns + 1
    for i = 2, #ns do
      if ns:sub(i, i) ~= "0" then
        b, bpos = tonumber(ns:sub(i, i)), i
        break
      end
    end
    -- use 1st but not max
    local ret = (#ns - 1) * 9 * (a - 1)
    -- don't use 1st
    ret = ret + 81 * mfl((#ns - 1) * (#ns - 2) / 2)
    -- use 1st by max
    if bpos <= #ns then
      ret = ret + b + 9 * (#ns - bpos)
    end
    print(ret)
  end
else
  if #ns < 3 then print(0)
  else
    local a = tonumber(ns:sub(1, 1))
    local b, bpos = 0, #ns + 1
    for i = 2, #ns do
      if ns:sub(i, i) ~= "0" then
        b, bpos = tonumber(ns:sub(i, i)), i
        break
      end
    end
    local c, cpos = 0, #ns + 1
    for i = bpos + 1, #ns do
      if ns:sub(i, i) ~= "0" then
        c, cpos = tonumber(ns:sub(i, i)), i
        break
      end
    end
    -- don't use 1st
    ret = 729 * mfl((#ns - 1) * (#ns - 2) * (#ns - 3) / 6)
    -- use 1st but not max
    ret = ret + (a - 1) * 81 * mfl((#ns - 1) * (#ns - 2) / 2)
    -- use 1st by max
    if bpos <= #ns - 1 then
      -- don't use second
      ret = ret + 81 * mfl((#ns - bpos) * (#ns - bpos - 1) / 2)
      -- use 2nd but not max
      ret = ret + (b - 1) * 9 * (#ns - bpos)
      -- use 2nd by max
      if cpos <= #ns then
        ret = ret + c + 9 * (#ns - cpos)
      end
    end
    print(ret)
  end
end