LeetCode-in-Java

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

public class Solution {
    private static final int MOD = (int) 1e9 + 7;
    private static final int N = 16;
    private final long[] pow10 = new long[N];

    public int sumDecoded(long[] nums) {
        if (pow10[0] == 0) {
            pow10[0] = 1;
            for (int i = 1; i < N; ++i) {
                pow10[i] = pow10[i - 1] * 10;
            }
        }
        long sum = 0;
        for (long num : nums) {
            int w = (int) (num % 10);
            long v = num / 10;
            int len = 1;
            while (v >= pow10[len]) {
                len++;
            }
            long base = pow10[len - w];
            long x = v / base;
            long y = v % base;
            sum += pow(x, y);
        }
        return (int) (sum % MOD);
    }

    private long pow(long x, long n) {
        long result = 1;
        while (n > 0) {
            if ((n & 1) == 1) {
                result = result * x % MOD;
            }
            x = x * x % MOD;
            n >>= 1;
        }
        return result;
    }
}