php 如何计算整数数组中所有可能组合的和?

5anewei6  于 2023-02-11  发布在  PHP
关注(0)|答案(2)|浏览(100)

给定一个正整数数组a,我想计算每个可能的a[i] ∘ a[j]sum,其中a[i] ∘ a[j]分别是a[i]a[j]的字符串表示的连接。
示例

For a = [10, 2], the output should be solution(a) = 1344.

a[0] ∘ a[0] = 10 ∘ 10 = 1010,
a[0] ∘ a[1] = 10 ∘ 2 = 102,
a[1] ∘ a[0] = 2 ∘ 10 = 210,
a[1] ∘ a[1] = 2 ∘ 2 = 22.
So the sum is equal to 1010 + 102 + 210 + 22 = 1344.

For a = [8], the output should be solution(a) = 88.

For a = [1, 2, 3], the output should be solution(a) = 198.

a[0] ∘ a[0] = 1 ∘ 1 = 11,
a[0] ∘ a[1] = 1 ∘ 2 = 12,
a[0] ∘ a[2] = 1 ∘ 3 = 13,
a[1] ∘ a[0] = 2 ∘ 1 = 21,
a[1] ∘ a[1] = 2 ∘ 2 = 22,
a[1] ∘ a[2] = 2 ∘ 3 = 23,
a[2] ∘ a[0] = 3 ∘ 1 = 31,
a[2] ∘ a[1] = 3 ∘ 2 = 32,
a[2] ∘ a[2] = 3 ∘ 3 = 33.
The total result is 11 + 12 + 13 + 21 + 22 + 23 + 31 + 32 + 33 = 198.
z31licg0

z31licg01#

可以使用以下PHP代码解决上述任务:
注意:$a =整型数组,$result =整型

function solution($a) {
    $result = 0;
    for($i=0;$i<count($a);$i++) {
        for($j=0;$j<count($a);$j++) {
            $result += (int)$a[$i].$a[$j];
        }
    }
    return $result;
}

试试我上面的解决方案。

7z5jn7bk

7z5jn7bk2#

此问题的解决方案:

def solution(a):
    lowSum = 0
    cnt = 0
    for i in range(len(a)):
        lowSum += a[i];

    cnt += lowSum * len(a)

    for j in range(len(a)): 
        size = len(str(a[j]))
        offset = iPower(10, size)
        cnt = cnt + lowSum * offset

    return cnt

def iPower(base, power):
    result = 1
    for i in range(1,power+1):
        result *= base
    return result

相关问题