본문 바로가기

알고리즘(w.KOTLIN)/탐색

[백준][1748][KOTLIN] 수 이어 쓰기1

728x90

https://www.acmicpc.net/problem/1748

 

1748번: 수 이어 쓰기 1

첫째 줄에 N(1 ≤ N ≤ 100,000,000)이 주어진다.

www.acmicpc.net

문제 풀이

1. 각 자리수가 같은 숫자의 범위를 탐색하여 결과를 구한다.

2. 입력이 1억이므로 전체 탐색을 해도 시간 초과 되지 않는다.

코드

import java.io.*

fun main(args: Array<String>) {
    val br = BufferedReader(InputStreamReader(System.`in`))
    val N = br.readLine()
    var result = 0

    if (N.length == 1) {
        result = N.toInt()
    } else {
        for (i in 1..N.toInt()) {
            if (i in 1..9) {
                result += 1
            } else if (i in 10..99) {
                result += 2
            } else if (i in 100..999) {
                result += 3
            } else if (i in 1000..9999) {
                result += 4
            } else if (i in 10000..99999) {
                result += 5
            } else if (i in 100000 ..999999) {
                result += 6
            } else if (i in 1000000 ..9999999) {
                result += 7
            } else if (i in 10000000 ..99999999) {
                result += 8
            } else {
                result += 9
            }
        }
    }

    println(result)
}
728x90