main.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func main() {
  6. // The least tidy number starts with n is nnnn..., array of ones is a faster way to work it out.
  7. ones := make([]int, 20)
  8. ones[1] = 1
  9. for i := 2; i < 20; i++ {
  10. ones[i] = ones[i-1]*10 + 1
  11. }
  12. // 1, 10, 100, 1000, ...
  13. base := make([]int, 20)
  14. base[1] = 1
  15. for i := 2; i < 20; i++ {
  16. base[i] = base[i-1] * 10
  17. }
  18. var T, N int
  19. fmt.Scan(&T)
  20. for cid := 1; cid <= T; cid++ {
  21. fmt.Scan(&N)
  22. cnt := 0
  23. for n := N; n != 0; n /= 10 {
  24. cnt++ // Count the digits of N
  25. }
  26. fmt.Printf("Case #%d: %d\n", cid, tidy(ones, base, N, cnt))
  27. }
  28. }
  29. func tidy(ones, base []int, num, cnt int) int {
  30. if cnt == 1 { // Has only one digit, returns itself.
  31. return num
  32. }
  33. highest := num / base[cnt]
  34. least := highest * ones[cnt]
  35. if num == least { // Is valid.
  36. return num
  37. } else if num < least { // Smaller than the least num starts with n, returns (n-1)9999...
  38. return (highest-1)*base[cnt] + 9*ones[cnt-1]
  39. } else { // Keep the highest digit, tidy up the remaining part.
  40. return highest*base[cnt] + tidy(ones, base, num-highest*base[cnt], cnt-1)
  41. }
  42. }