PTA basic 1056 组合数的和 (15 分) c++语言实现(g++)

给定 N 个非 0 的个位数字,用其中任意 2 个数字都可以组合成 1 个 2 位的数字。要求所有可能组合出来的 2 位数字的和。例如给定 2、5、8,则可以组合出:25、28、52、58、82、85,它们的和为330。

输入格式:

输入在一行中先给出 N(1 < N < 10),随后给出 N 个不同的非 0 个位数字。数字间以空格分隔。

输出格式:

输出所有可能组合出来的2位数字的和。

输入样例:

3 2 8 5
 

输出样例:

330

数字按字符输入, 然后经过排列组合后 转数字累加

 

#include <iostream>
#include <string>
#include <vector>
using namespace std;
//排列组合 N个数字组合成两位数的 结果有A(N,2)   (N*N-1)种
int main(){
    int n,sum{0};
    char c;
    vector<char> charList;
    string temp;
    cin >>n;
    for(int i=0;i<n;i++){
        cin >> c;
        charList.push_back(c);
    }
    for(int i=0;i<n;i++){
        for(int j=i+1;j<n;j++){
            temp+=charList[i];
            temp+=charList[j];
            sum+=stoi(temp);
            temp.clear();
        }
    }
    for(int i=n-1;i>=0;i--){
        for(int j=i-1;j>=0;j--){
            temp+=charList[i];
            temp+=charList[j];
            sum+=stoi(temp);
            temp.clear();
        }
    }
    cout << sum<<endl;
    return 0;
}

 

posted @ 2021-05-09 20:10  keiiha  阅读(79)  评论(0编辑  收藏  举报