In: Computer Science
Given an array of positive integers a, your task is 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
So the sum is equal to 1010 + 102 + 210 + 22 = 1344.
There is only one number in a, and a[0] ∘a[0] = 8 ∘8 = 88, so the answer is 88.
Input/Output
A non-empty array of positive integers.
Guaranteed constraints:
1 ≤ a.length ≤ 105,
1 ≤ a[i] ≤ 106.
[Java] Syntax Tips
The answer to the question is given below.
The java code is given below.
import java.util.Scanner; /* scanner package for user input */
public class concatenationsSum /* concatenationsSum class for
calculations */
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of elements in the array :
");
int n=sc.nextInt();
System.out.println("Enter the elements of array: ");
int value;
int[] arr=new int[n]; /* array for storing n elements */
int sum=0; /* intializing sum as 0 */
for(int i=0;i<n;i++)
{
value=sc.nextInt();
arr[i]=value;
}
/* perfroming all concatenation's sum using two loops */
for(int i=0;i<n;i++)
{
String str1 = Integer.toString(arr[i]); /* converting integer to
string by toString() function */
for(int j=0;j<n;j++)
{
String str2 = Integer.toString(arr[j]);
String str3=str1+str2;
int num=Integer.parseInt(str3); /* converting String to integer by
parseInt() function */
sum=sum+num; /* adding every num to sum */
}
}
System.out.println("Total concatenationsum is : "+sum); /* printing
the value of sum */
}
}
The screenshot of the running code is given below.
The screenshot of sample input and output is given below in the
image.
If the answer helped please upvote it means a lot. For any query
please comment.