Problem:
B - Integer in Integer

Problem Statement

Given an integer interval \[A, B\] and an integer C, your job is to calculate the number of occurrences of C as string in the interval.

For example, 33 appears in 333 twice, and appears in 334 once. Thus the number of occurrences of 33 in \[333, 334\] is 3.

Input

The test case is given by a line with the three integers, A, B, C (0 \leq A \leq B \leq 10^{10000}, 0 \leq C \leq 10^{500}).

Output

Print the number of occurrences of C mod 1000000007.

Sample Input 1

1 3 2

Output for Sample Input 1

1

Sample Input 2

333 334 33

Output for Sample Input 2

3

Sample Input 3

0 10 0

Output for Sample Input 3

2

Solution in Scala (judge verdict: Accepted)

import scala.annotation.tailrec
import scala.io.StdIn._
object Main extends App {
  val mod = 1000000007L
  val Array(a, b, c) = readLine.trim.split(' ')
  val power = Array.fill(10001){1L}
  for (i ← power.indices.tail) power(i) = power(i - 1) * 10 % mod
  println(
    ((countBelow(b, c) - countBelow(a, c) + a.indices.dropRight(c.length - 1).count(a.startsWith(c, _))) % mod + mod) % mod
  )


  def countBelow(limit: String, target: String): Long = {
    val rights = limit.foldRight((List(0L), 1L)){case (v, (l, d)) ⇒ ((v.asDigit * d + l.head) % mod :: l, d * 10 % mod)}._1.drop(target.length)
    countBelow(limit, target, limit.length, 0, rights, 0)
  }
  @tailrec def countBelow(limit: String, target: String, length: Int, left: Long, rights: List[Long], result: Long = 0): Long = {
    rights match {
      case Nil ⇒ (result % mod + mod) % mod
      case r::rr ⇒
        limit.prefixCompare(target, limit.length - length) match {
          case 0 ⇒ countBelow(limit, target, length - 1, (left * 10 + limit(limit.length - length).asDigit) % mod, rr, (result + (if (target.head != '0') left else (left - 1))  * power(length - target.length) + (r + 1)) % mod)
          case 1 ⇒ countBelow(limit, target, length - 1, (left * 10 + limit(limit.length - length).asDigit) % mod, rr, (result + (if (target.head != '0') (left + 1) else left) * power(length - target.length)) % mod)
          case -1 ⇒ countBelow(limit, target, length - 1, (left * 10 + limit(limit.length - length).asDigit) % mod, rr, (result + (if (target.head != '0') left else (left - 1))  * power(length - target.length)) % mod)
          case o ⇒ ???
        }
    }
  }
  implicit class Wrap(val str: String){
    def prefixCompare(that: String, toIndex: Int): Int = {
      prefixCompare(str, that, toIndex, 0)
    }
    @tailrec private[this] def prefixCompare(a: String, b: String, aPosition: Int, bPosition: Int ): Int = {
      if (a.indices.contains(aPosition) && b.indices.contains(bPosition)) {
        a(aPosition).compareTo(b(bPosition)) match {
          case 0 ⇒ prefixCompare(a, b, aPosition + 1, bPosition + 1)
          case o ⇒ if (o > 0) 1 else -1
        }
      }else 0
    }
  }
}