Round the given number to nearest multiple of 10 | Set | Java 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
class GFG { static void roundToNearest ( StringBuilder str , int n ) { if ( str . toString ( ) == " " ) return ; if ( str . charAt ( n - 1 ) - '0' <= 5 ) { str . setCharAt ( n - 1 , '0' ) ; System . out . print ( str . substring ( 0 , n ) ) ; } else { int carry = 0 ; str . setCharAt ( n - 1 , '0' ) ; int i = n - 2 ; carry = 1 ; while ( i >= 0 && carry == 1 ) { int currentDigit = str . charAt ( i ) - '0' ; currentDigit += carry ; if ( currentDigit > 9 ) { carry = 1 ; currentDigit = 0 ; } else carry = 0 ; str . setCharAt ( i , ( char ) ( currentDigit + '0' ) ) ; i -- ; } if ( carry == 1 ) System . out . print ( carry ) ; System . out . print ( str . substring ( 0 , n ) ) ; } } public static void main ( String [ ] args ) { StringBuilder str = new StringBuilder ( "99999999999999993" ) ; int n = str . length ( ) ; roundToNearest ( str , n ) ; } }