1006 换个格式输出整数 (15分)(两种方法)

80 篇文章 0 订阅
15 篇文章 0 订阅

让我们用字母 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>
#include<map>
#include<string> 
#include<set>
#include<stack>
#include<queue>
#include<algorithm>
#include<unordered_set>
using namespace std;
int main() {
	int n;
	cin>>n;
	int count=0;
	int a[3]={0};//定义一个数组
	int i=0;
	while(n){
		a[i++]=n%10;//求余,最后从后往前就是百十个位
		n/=10;
		count++;
	} 
	if(count==3){
		for(int j=0;j<a[2];j++){
			cout<<"B";
		}
		for(int j=0;j<a[1];j++){
			cout<<"S";
		}
		for(int j=1;j<=a[0];j++){
			cout<<j;
		}
	}
	else if(count==2){
		for(int j=0;j<a[1];j++){
			cout<<"S";
		}
		for(int j=1;j<=a[0];j++){
			cout<<j;
		}
	}
	else if(count==1){
		for(int j=1;j<=a[0];j++){
			cout<<j;
		}
	}
	return 0;
}


第二种方法,运用字符串,由于字符串的size可以算出有多少位,所以直接写就行,string更简单

#include <iostream>
#include<map>
#include<string> 
#include<set>
#include<stack>
#include<queue>
#include<algorithm>
#include<unordered_set>
using namespace std;
int main() {
	string s;
	cin>>s;
	int len=s.size();
	if(len==3){
		for(int j=0;j<s[0]-'0';j++){
			cout<<"B";
		}
		for(int j=0;j<s[1]-'0';j++){
			cout<<"S";
		}
		for(int j=1;j<=s[2]-'0';j++){
			cout<<j;
		}
	}
	else if(len==2){
		for(int j=0;j<s[0]-'0';j++){
			cout<<"S";
		}
		for(int j=1;j<=s[1]-'0';j++){
			cout<<j;
		}
	}
	else{
		for(int j=1;j<=s[0]-'0';j++){
			cout<<j;
		}
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_努力努力再努力_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值