✍个人博客:https://blog.csdn.net/Newin2020?spm=1011.2415.3001.5343
📚专栏地址:PAT题解集合
📝原题地址:题目详情 - 1073 Scientific Notation (pintia.cn)
🔑中文翻译:科学计数法
📣专栏定位:为想考甲级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 ] [+-][1-9] [+−][1−9]
.
[ 0 − 9 ] + E [ + − ] [ 0 − 9 ] + [0-9]+E[+-][0-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
思路
- 先处理字符串的正负号,如果是负号直接输出,如果是正号则忽略。
- 找到
E
在字符串中的位置k
,取出.
左右的数字并合在一起得到字符串a
,例如 1.234 1.234 1.234=>
1234 1234 1234 。 - 将
E
之后的指数取出来,并转换成整数num
,这里要用到的是c++
自带的函数stoi
,它的功能是将字符串转换成整数。并且为了方便后续处理,我们这里将num
加上1
。 - 判断指数的大小:
- 如果指数为负数,则小数点需要往左移动
-num
位(注意这里的num
之前已经加一了)。例如, + 1.234 E − 03 +1.234E-03 +1.234E−03=>
0.001234 0.001234 0.001234 。 - 如果指数大小大于等于
a
的长度,则需要在a
的后面加上num - a.size()
个0
(注意这里的num
之前已经加一了),例如, + 1.234 E + 04 +1.234E+04 +1.234E+04=>
12340 12340 12340 。 - 如果指数大小大于
0
但是小于等于a
的长度,则需要将a
用.
划分成左右两部分,左部分是0 ~ num
,右部分是num
以后的数字。例如, + 1.234 E + 02 +1.234E+02 +1.234E+02=>
12.34 12.34 12.34 。
- 如果指数为负数,则小数点需要往左移动
- 输出
a
即为最终结果。
代码
#include<bits/stdc++.h>
using namespace std;
int main()
{
string x;
cin >> x;
if (x[0] == '-') cout << '-'; //处理正负号
int k = x.find('E'); //找到E的位置
string a = x[1] + x.substr(3, k - 3); //取出有效数字
string b = x.substr(k + 1); //取出指数
int num = stoi(b); //stirng -> int
num++; //加1,方便后续处理
if (num <= 0) //指数为负
a = "0." + string(-num, '0') + a;
else if (num >= a.size()) //指数大于等于a的长度
a += string(num - a.size(), '0');
else //指数大于0且小于a的长度
a = a.substr(0, num) + '.' + a.substr(num);
cout << a << endl;
return 0;
}