(PAT 1073) Scientific Notation (字符串模拟题)
Scientific notation is the way that scientists easily handle very large numbers or very small numbers. The notation matches the regular expression [+-][1-9].
[0-9]+E[+-][0-9]+ which means that the integer portion has exactly one digit, there is at least one digit in the fractional portion, and the number and its exponent’s signs are always provided even when they are positive.
Now given a real number A in scientific notation, you are supposed to print A in the conventional notation while keeping all the significant figures.
Input Specification:
Each input contains one test case. For each case, there is one line containing the real number A in scientific notation. The number is no more than 9999 bytes in length and the exponent’s absolute value is no more than 9999.
Output Specification:
For each test case, print in one line the input number A in the conventional notation, with all the significant figures kept, including trailing zeros.
Sample Input 1:
+1.23400E-03
Sample Output 1:
0.00123400
Sample Input 2:
-1.2E+10
Sample Output 2:
-12000000000
解题思路:
模拟题,利用string读入数据
首先得到小数点的位置,然后扫描得到E的位置,判断E后面的是正数还是负数,然后读取指数a
如果E后面是正数,则将小数点与小数点后面那个数交换a次,如果小数点到达字符串末尾,那么就再字符串末尾补0并交换之
如果E后面是负数,则将小数点与小数点前面那个数交换a次,如果小数点到达字符串头,那么就在字符串头位置插入0
最后去掉正数符号和字符串末尾的小数点
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
string scentificNotion;
int main() {
cin >> scentificNotion;
string indexes,bases;
int dotPos;
bool bpostive = true;
for (int i = 0; i < scentificNotion.length(); ++i) {
if (scentificNotion[i] == '.') {
dotPos = i;
}
if (scentificNotion[i] == 'E') {
if (scentificNotion[i + 1] == '+') bpostive = true;
else bpostive = false;
for (int j = i + 2; j < scentificNotion.length(); ++j) {
indexes += scentificNotion[j];
}
break;
}
bases += scentificNotion[i];
}
if (bpostive) { //正数的情况
for (int i = 0; i < stoi(indexes); ++i) {
if (dotPos == bases.length() - 1) {
bases += '0';
swap(bases[dotPos], bases[dotPos + 1]);
dotPos++;
}
else {
swap(bases[dotPos], bases[dotPos + 1]);
dotPos++;
}
}
}
else { //负数的情况
for (int i = 0; i < stoi(indexes); ++i) {
if (dotPos == 1) {
bases.insert(1, "0");
swap(bases[1], bases[2]);
}
else {
swap(bases[dotPos], bases[dotPos - 1]);
dotPos--;
}
}
}
if (bases[0] == '+') {
bases.erase(bases.begin());
}
if (bases[bases.length() - 1] == '.') {
bases.erase(bases.end() - 1);
}
if (bases[1] == '.' || bases[0] == '.') {
if (bases[1] == '.') {
bases.insert(1, "0");
}
if (bases[0] == '.') {
bases.insert(0, "0");
}
}
cout << bases << endl;
system("PAUSE");
return 0;
}
还没有评论,来说两句吧...