Official

B - Broken Rounding Editorial by en_translator


Let us consider a smart way to round an integer off to the nearest \(10^k\).
First, when rounding off to the nearest \(10^k\), we don’t need to care the digits up to \(10^{k-2}\)’s places.
Reason: because we round down if \(10^{k-1}\)’s place is \(4\) or less, and round up if it is \(5\) or more. (Note: the definition of rounding in the problem statement is equivalent to the common one.)
Therefore, an integer \(X\) can be rounded off to the nearest \(10^k\) as follows.

  • First, we divide \(X\) by \(10^{k-1}\) (rounding down).
    • This makes \(10^{k-1}\)’s place the \(1\)’s place, and the \(10^{k-2}\)’s place and below are temporarily lost.
  • Let \(m\) be the \(1\)’s place of \(X\) (\(=\) the remainder of \(X\) divided by \(10\)).
    • If \(m \le 4\), subtract \(m\) from \(X\) and multiply \(X\) by \(10^{k-1}\) (this achieves rounding down).
    • Otherwise (if \(m \ge 5\)), add \(10-m\) to \(X\) and multiply \(X\) by \(10^{k-1}\) (this achieves rounding up).
    • Note that, by both of the operations above, \(10^{k-1}\)’s place and below of \(X\) becomes \(0\).

You can get accepted for this problem by implementing these steps. We can complete these operation within an integer type.

Sample code (C++):

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

posted:
last update: