小蓝最近在研究一种浮点数的表示方法:RR 格式。
对于一个大于 00 的浮点数 dd,可以用 RR 格式的整数来表示。
给定一个转换参数 nn,将浮点数转换为 RR 格式整数的做法是:
- 将浮点数乘以 2n2n;
- 四舍五入到最接近的整数。
输入格式
一行输入一个整数 nn 和一个浮点数 dd,分别表示转换参数,和待转换的浮点数。
输出格式
输出一行表示答案:dd 用 RR 格式表示出来的值。
数据范围
用 ll 表示将 dd 视为字符串时的长度。
对于 50%50% 的评测用例:1≤n≤101≤n≤10,1≤l≤151≤l≤15。
对于 100%100% 的评测用例:1≤n≤10001≤n≤1000,1≤l≤10241≤l≤1024;保证 dd 是小数,即包含小数点。
输入样例:
2 3.14
输出样例:
13
样例解释
3.14×22=12.563.14×22=12.56,四舍五入后为 1313。
题解:
本来看到1024位数和1000次方,就以为是有什么小技巧在里面,但是,什么都没有发现。
计算了一下,1024*1000才不过7次级,就是一道普通的高精度运算题,使用字符串。
普通地每一位乘2,大于十就进位。
在四舍五入的时候要注意一下,是否前面有9,是否有很多9,是否要字符串长度加一,比如999.75四舍五入是1000,这个1要处理,其他就没了。
代码:
cpp
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<iomanip>
#include<queue>
#include<stack>
#include<vector>
#include<unordered_set>
#include<unordered_map>
#include<map>
#include<set>
using namespace std;
typedef long long int ll;
int n;
string s;
string ride(string s){
string a;
bool pl=false;
for(int i=s.size()-1;i>=0;i--){
if(s[i]=='.'){
a='.'+a;
}
else{
//cout << "s[i]: " << s[i] << "\n";
int t=(s[i]-48)*2;
char ch=(t%10)+48;
a=ch+a;
if(pl){
a[0]++;
pl=false;
}
if(t>=10){
if(i==0){
a='1'+a;
}
pl=true;
}
//cout << a << "\n";
}
}
//cout << a << "\n";
return a;
}
int main(){
cin >> n;
cin >> s;
for(int i=0;i<n;i++){
string a=ride(s);
s=a;
}
//cout << s << "\n";
for(int i=0;i<s.size();i++){
if(s[i]=='.'){
if((s[i+1]-48)>=5){
int t=i-1;
bool x=false;
while(s[t]=='9'){
s[t]='0';
t--;
if(t == -1){
cout << '1';
x=true;
break;
}
}
if(!x){
s[t]++;
}
for(int j=0;j<i;j++){
cout << s[j];
}
}
else{
for(int j=0;j<i;j++){
cout << s[j];
}
}
}
}
}