# Total of all unique numbers | AlphaSense coding question

## Total of all unique numbers

Write a program for the following input and expected output.

Input: Comma separated numbers as string

Output: Total of all unique numbers

Notes:

1. The input string can have invalid characters, spaces, or empty values.
2. The maximum length of the input can be 50K characters. So make sure that your solution is optimized for performance.
3. Please use features of Java 8 or higher.
4. Follow all the coding practices and guidelines.

Example:

Input: "1,3,1,2,3"

Output: 6

Example:

Input: "1,,1,a,3"

Output: 4

Code (Java 15):-

import java.util.*;

public class Main
{
public static int getTotal(String input)
{
HashMap<Integer,Integer> dic=new HashMap<Integer,Integer>();
int sum=0;
String[] str=input.split(",",0);
for(int i=0;i<str.length;i++)
{
try{
int val=Integer.parseInt(str[i]);
if(!dic.containsKey(val))
{
dic.put(val,1);
sum+=val;
}
}
catch(Exception e){
}
}
return sum;
}
// Driver function
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
String input=sc.next();
System.out.println(getTotal(input));
}
}

Output:-

1,a,1,2,3
6

### Recommended Post :-

HCL Coding Questions:-

Capgemini Coding Questions:-
iMocha coding Questions:-
Tech Mahindra coding questions:-
Unthinkable Solutions coding questions:-