题目描述
正整数A的“DA(为1位整数)部分”定义为由A中所有DA组成的新整数PA。例如:给定A = 3862767,DA = 6,则A的“6部分”PA是66,因为A中有2个6。 现给定A、DA、B、DB,请编写程序计算PA + PB。
输入描述:
输入在一行中依次给出A、DA、B、DB,中间以空格分隔,其中0 < A, B < 1010。
输出描述:
在一行中输出PA + PB的值。
输入例子:
3862767 6 13530293 3
输出例子:
399
我的代码
package pat;
import javax.swing.*;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* PAT乙级:部分A+B
*/
public class patSecondary06 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String str = sc.nextLine();
String[] strings = str.split(" ");
solution(strings);
}
sc.close();
}
private static void solution(String[] strings) {
try {
String strA = strings[0];
String strDa = strings[1];
String strB = strings[2];
String strDb = strings[3];
int A = pattern(strA, strDa);
int B = pattern(strB, strDb);
System.out.println(A + B);
} catch (Exception e) {
System.out.println(e);
}
}
private static int pattern(String strA, String strDa) {
// 根据指定的字符构建正则
Pattern pattern = Pattern.compile(strDa);
// 构建字符串和正则的匹配
Matcher matcher = pattern.matcher(strA);
int count = 0, num = 0;
while (matcher.find()) {
count++;
}
StringBuffer temp = new StringBuffer();
if (count != 0) {
for (int i = 0; i < count; i++) {
temp.append(strDa);
}
String numN = String.valueOf(temp);
num = Integer.parseInt(numN);
} else {
num = 0;
}
return num;
}
}