PAT 乙级 1016.部分A+B C++/Java
正整数 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的值。
输入样例 1:
3862767 6 13530293 3
输出样例 1:
399
输入样例 2:
3862767 1 13530293 8
输出样例 2:
0
思路:
先分别找出DA、DB在A、B中出现的次数countA、countB,再分别得出整数PA、PB,输出两者和即可。
C++实现:
#include <iostream> using namespace std; int main() { string A, B; char DA, DB; int countA = 0, countB = 0; cin >> A >> DA >> B >> DB; for (int i = 0; i < A.length(); i++) { if (A[i] == DA) { countA++; } } for (int i = 0; i < B.length(); i++) { if (B[i] == DB) { countB++; } } int resA = 0, resB = 0; for (int i = 0; i < countA; i++) { int rA = DA - '0'; resA = resA * 10; resA += rA; } for (int i = 0; i < countB; i++) { int rB = DB - '0'; resB = resB * 10; resB += rB; } cout << resA + resB << endl; }
Java实现:
1 import java.util.Scanner; 2 3 public class Main { 4 public static void main(String[] args) { 5 Scanner input = new Scanner(System.in); 6 String str = input.nextLine(); 7 String[] arr = str.split("\\s+"); 8 int result1 = sum(arr[0], arr[1]); 9 int result2 = sum(arr[2], arr[3]); 10 int sum = result1 + result2; 11 System.out.print(sum); 12 } 13 14 public static int sum(String x, String y) { 15 int result = 0; 16 int t = Integer.parseInt(y); //字符转数字 17 int[] array = stoi(x); 18 for (int i = 0; i < x.length(); i++) { 19 if (array[i] == t) { 20 result = result * 10 + t; 21 } 22 } 23 return result; 24 } 25 26 public static int[] stoi(String x) { //字符串转整形数组 27 int[] a = new int[x.length()]; 28 for (int i = 0; i < x.length(); i++) { //字符串转为整形数组 29 char c = x.charAt(i); 30 a[i] = (int) (c - '0'); 31 } 32 return a; 33 } 34 }