将数字转换为中文大写(缩写)

这个题目看似很简单,但是搞了好久没有搞出来,也不知道是否全部AC,记录一下

将阿拉伯数字转换成中文大写(缩写)注意用语习惯:

“壹贰叁肆伍陆柒捌玖拾零佰仟万亿” 对应 “1234567890SBQWY”

输入:123

输出:1B2S3

输入:123456

输出:1S2W3Q4B5S6

方法一、将输入当作数字处理

思路:

main{

1、分别准备两个数组:
    v_num = [100000000,10000,1000,100,10,1];
    v_word = ["Y","W","Q","B","S"];
2、准备一个空字符 res = "";
3、调用process函数
4、输出
}

process:使用取商和取余的方法,如果商>=10则递归调用process,否则直接下一步
#include
#include
#include
using namespace std;

void process(int n, vector v_num, vector v_word,string& res) {
	if (n == 0) {
		res += "0";
	}
	for (int i = 0; i < v_num.size(); ++i) {
		int shang = n / v_num[i];//商
		if (shang != 0) {//如果商不等于0,则找到了合适的数
			if (shang != n) {//如果不等于n说明shang的除数不是1
				int yushu = n % v_num[i];//取余数
				if (shang >= 10)//如果余数大于等于10递归
					process(shang, v_num, v_word, res);
				else //否则直接追加到res后面
					res += to_string(shang);
				res += v_word[i];//然后将"Y","W"..对于的添加进来
				if (yushu < v_num[i + 1]) {//处理103,1024等
					res += "0";
				}
				n = yushu;
			}
			if (shang == n) {//如果商的除数是1则不用添加"Y","W"...字符
				res += to_string(shang);
			}
		}
	}
}
int main() {
	long n;
	while (cin >> n) {
		vector v_num = { 100000000,10000,1000,100,10,1};
		vector v_word = { "Y","W","Q","B","S" };
		string res = "";
		process(n, v_num, v_word, res);
		cout << res;
	}

}
0
0
1
1
2
2
12
1S2
123
1B2S3
103
1B03
1234
1Q2B3S4
12304
1W2Q3B04
12345
1W2Q3B4S5
123456
1S2W3Q4B5S6
1234567
1B2S3W4Q5B6S7
1234567809
1S2Y3Q4B5S6W7Q8B09

方法二、将输入当作字符串处理

#include
#include

using namespace std;

int main()
{
	long n;
	while (cin >> n) {
		string res, str;
		str = to_string(n);
		int len = str.size(), k = 0;
		for (int i = 0; i < str.size(); i++)
		{
			k = len % 4;
			if (str[i] != '0')
			{
				switch (k)
				{
				case 1:
					res = res + str[i]; break;
				case 2:
					res = res + str[i] + "S"; break;
				case 3:
					res = res + str[i] + "B"; break;
				case 0:
					res = res + str[i] + "Q"; break;
				}
			}
			else{//如果出现103等情况
				res = res + str[i];
			}
			if (len == 5)
				res += "W";
			else if (len == 9)
				res += "Y";
			len--;
		}
		cout << res << endl;
	}
	
	return 0;
}

注意要遗漏"0"的判断如103,1023等

你可能感兴趣的:(Simple,Practice)