2544. Alternating Digit Sum

2023. 1. 28. 23:38Algorithm/Leetcode, Lintcode, HackerRank, etc.

    목차
반응형

Kotlin

class Solution {
    fun alternateDigitSum(n: Int): Int {
        val s = n.toString()
        var sum: Int = 0
        var toggle: Boolean = true

        for (i in 0 until s.length) {
            val digit = Character.getNumericValue(s[i])
            if (true == toggle) {
                sum += digit
            } else {
                sum += -1 * digit
            }

            toggle = !toggle  
        }

        return sum
    }
}
반응형