Given a non-negative integer X, perform the following operation for i=1,2.....K in this order and find the resulting X.
- Round X off to the nearest 10^i.
- Formally, replace X with Y that is "the largest multiple of 10^i that minimizes |Y-X|."
- Here are some examples:
- Rounding 273 off to the nearest 10^2 yields 300.
- Rounding 999 off to the nearest 10^3 yields 1000.
- Rounding 100 off to the nearest 10^10 yields 0.
- Rounding 1015 off to the nearest 10^1 yields 1020
Constraints
- X and K are integers.
- 0 < X < 10^15
- 1≤K≤15
Input
The input is given from Standard Input in the following format:
X K
Output
Print the answer as an integer.
Sample Input 1
2048 2
Sample Output 1
2100
X changes as 2048→2050→2100 by the operations.
Sample Input 2
1 15
Sample Output 2
0
Sample Input 3
999 3
Sample Output 3
1000
Sample Input 4
314159265358979 12
Sample Output 4
314000000000000
XXmay not fit into a 32-bit integer type.
———————————————————假装是分割线——————————————————
开始我以为这只是一道简单的 四 舍 五 入(是我太天真了)
幸亏样例给了一个314159265358979这个,如果用整数的进行对10 或者10 的几次方取余(这个十的几次方我只会用pow(10,n)我不会(委屈 )),用那个pow是会失效的,好像因为这个要弄浮点型还是咋的,然后我就没多想就改用字符存储了。下面是我修改无数遍终于AC的代码
#include<bits/stdc++.h>
using namespace std;
int a[1000];
bool x=false;
int main()
{
int i,k;
string s;
cin>>s>>k;//以字符串输入
a[0]=s.length();//求位数
for(int i=1; i<=a[0]; i++)
{
a[i]=s[a[0]-i]-'0';//字符转为数字
}
for(i=1;i<=k;i++)//循环k次
{
if(a[i]>=5&&a[i]<=9)//满足“五入”条件
{
a[i]=0;//本位变为0
a[i+1]++;//向前进位
}
else
{
a[i]=0;
}
if(a[i+1]>=10)//向前进位导致前位满10
{
a[i+2]++;//再进位
a[i+1]-=10;
}
}
if(a[0]>k)//k次循环完成,但存在仍需向前进位的可能(考虑x=9999999,k=3)
{
for(i=k-1;i<=a[0];i++)
{
if(a[i+1]>=10)
{
a[i+2]++;
a[i+1]-=10;
}
}
}
for(i=a[0]+1;i>=1;i--)
{
if(x==false&&a[i]==0)
{
continue;
}
x=true;//从要输出第一个不为零的数开始,变为true(防止最高位的前面输出0)
cout<<a[i];
}
if(x==false)
{
cout<<0;
}
return 0;
}
附上官方题解:
#include<bits/stdc++.h>
using namespace std;
int main(){
long long x,k;
cin >> x >> k;
long long pow10=1;
for(long long i=0;i<k;i++){
x/=pow10;
long long m=(x%10);
if(m<=4){x-=m;}
else{x+=(10-m);}
x*=pow10;
pow10*=10;
}
cout << x << "\n";
return 0;
}
第一次发这个没什么经验,主要是纪念一下脑卡导致改了两个小时代码(〒︿〒)
改对了就很开心ヾ(✿゚▽゚)ノ