C++ Program to find rounded numbers to save kingdom

Suppose we have a string S where a decimal real number is given. There is a king called Amal, and his son Bimal is in a kingdom. There are other citizens also. They lived happily until great trouble came into the Kingdom. The monsters settled there. Most damage those strange monsters inflicted upon the kingdom was that they loved high precision numbers. As a result, the Kingdom healers had already had three appointments with the merchants who sell, exactly 0.273549107 potion barrels. To deal with the problem somehow, the King Amal issued an order obliging rounding up all numbers to the closest integer to simplify calculations. Specifically, the order went like this −

  • If a number's integer part does not end with the digit 9 and its fractional part is strictly less than 0.5, then the rounded-up number coincides with the number’s integer part.

  • If a number's integer part does not end with the digit 9 and its fractional part is not less than 0.5, the rounded-up number is obtained if 1 is added to the last digit of the number’s integer part.

  • If the number’s integer part ends with the digit 9, to round up the numbers, report that as "Not possible".

We have to implement the logic to get the rounded number.

Problem Category

To solve this problem, we need to manipulate strings. Strings in a programming language are a stream of characters that are stored in a particular array-like data type. Several languages specify strings as a specific data type (eg. Java, C++, Python); and several other languages specify strings as a character array (eg. C). Strings are instrumental in programming as they often are the preferred data type in various applications and are used as the datatype for input and output. There are various string operations, such as string searching, substring generation, string stripping operations, string translation operations, string replacement operations, string reverse operations, and much more. Check out the links below to understand how strings can be used in C/C++.



So, if the input of our problem is like S = "3.14159", then the output will be 3


To solve this, we will follow these steps −

ret := a blank string
p := position of '.' in S
if S[p - 1] is same as '9', then:
   return "Not Possible"
   ret := ret concatenate (substring of S from index 0 to p-1) if S[p+1] < '5', otherwise (substring of S from index 0 to p-2) concatenate (S[p - 1] + 1)
return ret


Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
string solve(string S){
   string ret = "";
   int p = S.find('.');
   if (S[p - 1] == '9')
      return "Not Possible";
      ret += (S[p + 1] < '5' ? S.substr(0, p) : S.substr(0, p - 1) + string(1, (S[p - 1] + 1)));
      return ret;
int main(){
   string S = "3.14159";
   cout << solve(S) << endl;