Example 1: given the below input the output will be 2+13+8+22=45
Given Input
[2GSD#13x8xU343%^DGF1@22@]
Expected output
45
Example 2: given the below input the output will be 11+23+164+44=242
Given Input
x11@23@33S164DFS44_+}|#555
Expected output
242
Program:
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class SumOfEvenAndPrimeNumbers
{
public static void main (String[] args) throws java.lang.Exception
{
String str ="x11@23@33S164DFS44_+}|#555";
int sum = 0;
// fetching all digits
List<Integer> digits = getDigits(str);
for(Integer digit : digits) {
// checking whether number is even or prime
if(digit%2 == 0 || (digit != 1 && isPrime(digit))) {
sum = sum + digit;
}
}
System.out.println(sum);
}
private static boolean isPrime(int number) {
for(int i=2; i<=number/2; i++){
if(number % i == 0){
return false;
}
}
return true;
}
private static List<Integer> getDigits(String str) {
List<Integer> digits = new ArrayList<Integer>();
Matcher match = Pattern.compile("[0-9]+").matcher(str);
while (match.find()) {
digits.add(Integer.parseInt(match.group()));
}
return digits;
}
}
Output:
242
0 comments:
Post a Comment