PAT1005 Spell It Right

此题重点为用string接输入,int会溢出

#include 
#include 
#include 
#include 

using namespace std;

string transfer(int i){
    if(i == 0) return "zero";
    if(i == 1) return "one";
    if(i == 2) return "two";
    if(i == 3) return "three";
    if(i == 4) return "four";
    if(i == 5) return "five";
    if(i == 6) return "six";
    if(i == 7) return "seven";
    if(i == 8) return "eight";
    if(i == 9) return "nine";
    return "error";
}
int main()
{
    string input;
    int sum = 0;
    cin>>input;

    char inputArr[input.size() + 1];
    strcpy(inputArr,input.c_str());

    for(int i = 0; i < input.size(); i++){
        sum += inputArr[i] - '0';
    }

    vector<string> ansArr;
 //   cout<

    while(sum/10 != 0){
        ansArr.push_back(transfer(sum % 10));
        sum = sum/10;
    }
    ansArr.push_back(transfer(sum));
    for(int i = ansArr.size() - 1; i >= 0; i--){
        if(i != 0) cout<<ansArr[i]<<" ";
        else cout<<ansArr[i];
    }
    return 0;
}

你可能感兴趣的:(算法)