Skip to content

Instantly share code, notes, and snippets.

@theodoreLee
Created June 5, 2015 13:29
Show Gist options
  • Save theodoreLee/e2be20b1f69729dfbff3 to your computer and use it in GitHub Desktop.
Save theodoreLee/e2be20b1f69729dfbff3 to your computer and use it in GitHub Desktop.
import java.io.FileOutputStream
import scala.io.Source
object Counter {
val INPUT = "A-large-practice.in"
val OUTPUT = INPUT.takeWhile(_ != '.') + ".out2"
val isConsole = false
def main(args: Array[String]): Unit = {
val itr = Source.fromFile(INPUT).getLines()
val stream = if (isConsole) Console.out else new FileOutputStream(OUTPUT)
try {
Console.withOut(stream) {
val sets = itr.next().toInt
(1 to sets).foreach { set =>
val n = itr.next()
println(f"Case #$set: ${solve(n)}")
}
}
} finally {
stream.flush()
if (!isConsole) stream.close()
}
}
def solve(N:String):Long = {
val n = N.toLong
val nL = N.length
def count(accr:String, cnt:Long):Long = accr match {
case _ if accr == N => cnt
case _ if accr.length + 1 < nL =>
val newAccr = "1" + "0" * (accr.length / 2) + "9" * ((accr.length + 1) / 2)
count(newAccr.reverse, newAccr.toLong - accr.toLong + 1 + cnt)
case _ if accr.length < nL =>
val newAccr = "1" + "0" * (nL -1)
count(newAccr, newAccr.toLong - accr.toLong + cnt)
case _ =>
// n -1의 값을 reverse..
val newAccr = "1" + "0" * ((nL - 1) / 2) + (n - 1).toString.take(nL / 2).reverse
if (newAccr.reverse == newAccr || newAccr.toLong > n) n - accr.toLong + cnt
else n - newAccr.reverse.toLong + 1 + (newAccr.toLong - accr.toLong) + cnt
}
count("1", 1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment