PAT甲级1082 Read Number in Chinese:[C++题解]字符串处理
生活随笔
收集整理的這篇文章主要介紹了
PAT甲级1082 Read Number in Chinese:[C++题解]字符串处理
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 題目分析
- 題目來源
題目分析
來源:acwing
分析
從后往前,四位數作為1組來處理。每組單位最多是十百千,組間單位是萬和億。以123456789為例,分成三組為1,2345,6789,下面while循環便是此作用。
//4位一組作為1個數,放進numswhile(n) nums.push_back(n % 10000),n/= 10000;nums數組中存儲的是倒序:6789,2345,1。
下面使用三個string 數組進行映射:
num1[]:映射成漢語表示,ling,yi,er,... num2[]:組內單位:十百千 num3[]:組間單位:萬億難點在于對零的處理:
- 末尾ling去掉
- 不能有連續個ling
這里寫了一個函數check用來判斷末尾是否是ling
//使用substr庫函數,下面是求s字符串最后5個字符s.substr(s.size()-5)=="ling "用作讀者參考:要處理的特例舉例:
1,0000,0080 讀作: yi Yi ling ba Shi //中間只有1個零,要考慮清楚ac代碼
#include<bits/stdc++.h> using namespace std;string num1[] ={"ling","yi","er","san","si","wu","liu","qi","ba","jiu" };//判斷末尾是否是0 bool check(string s) {return s.size() >= 5 && s.substr(s.size()-5)=="ling "; }//處理4位數 string work(int n){vector<int> nums;while(n) nums.push_back(n%10) ,n/= 10;string num2[]={"","Shi","Bai","Qian"};//組內單位string res;for(int i = nums.size()-1; i>= 0; i--){int t = nums[i];//如果不是0if(t) res += num1[t]+" ";//轉化為中文讀法//如果是0,并且res末尾不是lingelse if(!check(res)) res += "ling ";// 不是0并且不是最后一個數(單位是個,不加),加上組內單位if(t && i) res += num2[i]+" ";}//去掉末尾零if (check(res)) res =res.substr(0,res.size()-5);return res; }int main(){int n;cin >> n;if(!n) cout<<"ling"<<endl;else{if(n<0) cout<<"Fu ",n= -n;vector<int> nums;string res;string num3[] ={"","Wan","Yi"};//4位一組作為1個數,放進numswhile(n) nums.push_back(n % 10000),n/= 10000;//最多nums中3個數//從高位遍歷for(int i =nums.size()-1;i>=0; i--){//每次取1組數int t =nums[i];if(res.size() && t<1000 && !check(res)) res += "ling ";if(t) res += work(t);//組間單位if(t && i) res += num3[i] +" ";}//去掉末尾零:末尾可能有多個,所以用whilewhile (check(res)) res =res.substr(0,res.size()-5);res.pop_back(); cout<<res<<endl;}}題目來源
PAT甲級1082 Read Number in Chinese
https://www.acwing.com/problem/content/1570/
總結
以上是生活随笔為你收集整理的PAT甲级1082 Read Number in Chinese:[C++题解]字符串处理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PAT甲级1077 Kuchiguse:
- 下一篇: PAT甲级1084 Broken Key