Round the given number to nearest multiple of 10 | Set | 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
def roundToNearest ( str , n ) : NEW_LINE INDENT if ( str == " " ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( ord ( str [ n - 1 ] ) - ord ( '0' ) <= 5 ) : NEW_LINE INDENT str = list ( str ) NEW_LINE str [ n - 1 ] = '0' NEW_LINE str = ' ' . join ( str ) NEW_LINE print ( str [ 0 : n ] ) NEW_LINE DEDENT else : NEW_LINE INDENT carry = 0 NEW_LINE str = list ( str ) NEW_LINE str [ n - 1 ] = '0' NEW_LINE str = ' ' . join ( str ) NEW_LINE i = n - 2 NEW_LINE carry = 1 NEW_LINE while ( i >= 0 and carry == 1 ) : NEW_LINE INDENT currentDigit = ord ( str [ i ] ) - ord ( '0' ) NEW_LINE currentDigit += carry NEW_LINE if ( currentDigit > 9 ) : NEW_LINE INDENT carry = 1 NEW_LINE currentDigit = 0 NEW_LINE DEDENT else : NEW_LINE INDENT carry = 0 NEW_LINE DEDENT str [ i ] = chr ( currentDigit + '0' ) NEW_LINE i -= 1 NEW_LINE DEDENT if ( carry == 1 ) : NEW_LINE INDENT print ( carry ) NEW_LINE DEDENT print ( str [ 0 : n ] ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = "99999999999999993" NEW_LINE n = len ( str ) NEW_LINE roundToNearest ( str , n ) NEW_LINE DEDENT