Given an array of positive integers a, I want to calculate the sum of every possible a[i] β a[j], where a[i] β a[j] is the concatenation of the string representations of a[i] and a[j] respectively.
Example
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.
>Solution :
The above task can be solved using the following PHP code:
Notes: $a = Integer array, $result = Integer
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;
}
Try my above solution.