PAT-乙-1084 1084 外觀數列 (20 分)
阿新 • • 發佈:2019-02-02
程式碼
#include <iostream> using namespace std; int main() { string d; int N; cin>>d>>N; while(--N){ string ans; char c = d[0]; int count = 0; for(int i=0; i<d.length(); i++){ if(d[i]==c){ count++; } else{ ans += c; ans += count + '0'; c = d[i]; count = 1; } } if(count>0){ ans += c; ans += count + '0'; } d = ans; } cout<<d<<endl; return 0; }
註解
1、注意–N與N–的區別
2、用char保留當前的字元,count來計數。如果遇到相同字元,count++即可,如果遇到不同字元,首先儲存字元和個數。然後用當前字元充當新結果。最後不要忘記加上結尾的那些字元和個數。