题目描述
给定一个数,请将该数各个位上数字反转得到一个新数。
这次与NOIP2011普及组第一题不同的是:这个数可以是小数,分数,百分数,整数。整数反转是将所有数位对调;小数反转是把整数部分的数反转,再将小数部分的数反转,不交换整数部分与小数部分;分数反转是把分母的数反转,再把分子的数反转,不交换分子与分母;百分数的分子一定是整数,百分数只改变数字部分。整数新数也应满足整数的常见形式,即除非给定的原数为零,否则反转后得到的新数的最高位数字不应为零;小数新数的末尾不为0(除非小数部分除了0没有别的数,那么只保留1个0);分数不约分,分子和分母都不是小数(约分滴童鞋抱歉了,不能过哦。输入数据保证分母不为0),本次没有负数。
输入格式
一个数s
输出格式
一个数,即s的反转数
输入输出样例
说明/提示
所有数据:
25%s是整数,不大于20位
25%s是小数,整数部分和小数部分均不大于10位
25%s是分数,分子和分母均不大于10位
25%s是百分数,分子不大于19位
(20个数据)
首先,我们看到这个题,易分析出这个题有四个步骤:拆分,翻转,去零,输出。
所以我们只要分开编出几个函数进行这几个操作即可。
经过观察,易发现:小数的小数部分需要去除的是后部的零,而其他的需要去除的是前部的零。
不多说了,直接上程序:(用的是对字符串的处理)(程序有点长,但思路非常简单易懂)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
| #include<bits/stdc++.h> #include <cstring> using namespace std; string qutou(string a) { int len; while(a[0]=='0'&&len!=1) { len=a.size(); a=a.substr(1,len-1); } return a; } string quwei(string a) { int len=a.size(); while(a[len-1]=='0') { a=a.substr(0,len-1 ); len--; } return a; } string fanzhuan(string a) { int len=a.size(); string b; for(int i=len-1;i>=0;i--) { b+=a[i]; } return b; } int main() { string front,behind,total; getline(cin,total); int len=total.size(),n=0,form=0; for(int i=0;;i++) { if(total[i]!='/'&&total[i]!='%'&&total[i]!='.') { front+=total[i]; } if(total[i]=='/') { form=1; n=i+1; break; } if(total[i]=='%') { form=2; break; } if(total[i]=='.') { form=3; n=i+1; break; } if(i==len-1) { form=4; break; } } if(form==1||form==3) { for(int j=n;j<=len-1;j++) { behind+=total[j]; } behind=fanzhuan(behind); } front=fanzhuan(front); front=qutou(front); if(form==1) { behind=qutou(behind); if(front=="\0") { cout<<"0/"<<behind; } else { cout<<front<<"/"<<behind; } } if(form==2) { front=qutou(front); if(front=="\0") { cout<<"0%"; } else { cout<<front<<"%"; } } if(form==3) { behind=quwei(behind); if(behind=="\0") { if(front=="\0") { front="0"; } cout<<front<<".0"; } else { cout<<front<<"."<<behind; } } if(form==4) { front=qutou(front); if(front=="\0") { cout<<"0"; } else { cout<<front; } } return 0; }
|