PAT 1006 换个格式输出整数

PAT 1006 换个格式输出整数

题目:

让我们用字母 B 来表示“百”、字母 S 表示“十”,用 12...n 来表示不为零的个位数字 n(<10),换个格式来输出任一个不超过 3 位的正整数。例如 234 应该被输出为 BBSSS1234,因为它有 2 个“百”、3 个“十”、以及个位的 4。

输入格式:

每个测试输入包含 1 个测试用例,给出正整数 n(<1000)。

输出格式:

每个测试用例的输出占一行,用规定的格式输出 n。

输入样例 1:

234

输出样例 1:

BBSSS1234

输入样例 2:

23

输出样例 2:

SS123

代码:

#include <iostream>

using namespace std;

int main()
{
    int unit,ten,hundred;
    int input;
    cin>>input;
    hundred = input/100;
    ten = (input-hundred*100)/10;
    unit = input%10;
    if(hundred > 0)
        for(int i = 0;i < hundred;++i)
            cout<<"B";
    if(ten > 0)
        for(int i = 0;i < ten;++i)
            cout<<"S";
    if(unit  > 0)
        for(int i = 0;i < unit;++i)
            cout<<i+1;
    return 0;
}

解析:

简单的数据转换.

(另一种思路可以作为字符串输入,字符串直接按位提取(干脆一起写出来得了= =))

#include <iostream>
#include <string>
using namespace std;

int main(void){
    string input;
    cin>>input;
    int len = input.size();
    int pos[3];
    for(int i = 0;i < len;++i){
        pos[i] = stoi(input.substr(i, 1));//substr转换为字符串再用stoi转换为数字
        for(int j = 0;j < pos[i];++j){
            if(i == len-3)		cout<<"B";
            else if(i == len-2)	cout<<"S";
            else if(i == len-1)	cout<<j+1;
        }
    }
}
原文地址:https://www.cnblogs.com/EPZ11/p/12312537.html