Broken Rounding(一道关于四舍五入的题)

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;
}

第一次发这个没什么经验,主要是纪念一下脑卡导致改了两个小时代码(〒︿〒)

改对了就很开心ヾ(✿゚▽゚)ノ

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飞快快超人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值