Round the given number to nearest multiple of 10 | Set | C ++ implementation of the approach ; Function to round the given number to the nearest multiple of 10 ; If string is empty ; If the last digit is less then or equal to 5 then it can be rounded to the nearest ( previous ) multiple of 10 by just replacing the last digit with 0 ; Set the last digit to 0 ; Print the updated number ; The number hast to be rounded to the next multiple of 10 ; To store the carry ; Replace the last digit with 0 ; Starting from the second last digit , add 1 to digits while there is carry ; While there are digits to consider and there is carry to add ; Get the current digit ; Add the carry ; If the digit exceeds 9 then the carry will be generated ; Else there will be no carry ; Update the current digit ; Get to the previous digit ; If the carry is still 1 then it must be inserted at the beginning of the string ; Prin the rest of the number ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void roundToNearest ( string str , int n ) { if ( str == " " ) return ; if ( str [ n - 1 ] - '0' <= 5 ) { str [ n - 1 ] = '0' ; cout << str . substr ( 0 , n ) ; } else { int carry = 0 ; str [ n - 1 ] = '0' ; int i = n - 2 ; carry = 1 ; while ( i >= 0 && carry == 1 ) { int currentDigit = str [ i ] - '0' ; currentDigit += carry ; if ( currentDigit > 9 ) { carry = 1 ; currentDigit = 0 ; } else carry = 0 ; str [ i ] = ( char ) ( currentDigit + '0' ) ; i -- ; } if ( carry == 1 ) cout << carry ; cout << str . substr ( 0 , n ) ; } } int main ( ) { string str = "99999999999999993" ; int n = str . length ( ) ; roundToNearest ( str , n ) ; return 0 ; }