LeetCode in Kotlin

4039. Sum of Decoded Numbers

Medium

You are given an integer array nums.

Each nums[i] is an encoded integer representing two positive integers xi and yi. To decode nums[i], define:

It is guaranteed that the decimal representation of di contains more than widthi digits. Therefore, both xi and yi contain at least one digit.

The decoded value of nums[i] is xiyi.

Return the sum of the decoded values of all elements in nums, modulo 109 + 7.

The floor() function returns the integer part of the division.

Example 1:

Input: nums = [231]

Output: 8

Explanation:

Example 2:

Input: nums = [2522,2101]

Output: 1649

Explanation:

Example 3:

Input: nums = [2301]

Output: 73741817

Explanation:

Constraints:

Solution

class Solution {
    private val pow10 = LongArray(N)

    fun sumDecoded(nums: LongArray): Int {
        if (pow10[0] == 0L) {
            pow10[0] = 1
            for (i in 1..<N) {
                pow10[i] = pow10[i - 1] * 10
            }
        }
        var sum: Long = 0
        for (num in nums) {
            val w = (num % 10).toInt()
            val v = num / 10
            var len = 1
            while (v >= pow10[len]) {
                len++
            }
            val base = pow10[len - w]
            val x = v / base
            val y = v % base
            sum += pow(x, y)
        }
        return (sum % MOD).toInt()
    }

    private fun pow(x: Long, n: Long): Long {
        var x = x
        var n = n
        var result: Long = 1
        while (n > 0) {
            if ((n and 1L) == 1L) {
                result = result * x % MOD
            }
            x = x * x % MOD
            n = n shr 1
        }
        return result
    }

    companion object {
        private val MOD = 1e9.toInt() + 7
        private const val N = 16
    }
}