Sunday, November 17, 2024
Google search engine
HomeData Modelling & AIRound the given number to nearest multiple of 10 | Set-2

Round the given number to nearest multiple of 10 | Set-2

Given a large positive integer represented as a string str. The task is to round this number to the nearest multiple of 10

Examples:

Input: str = “99999999999999993”
Output: 99999999999999990

Input: str = “99999999999999996” 
Output: 100000000000000000

Approach: A solution to the same problem has been discussed in this article which will not work for large numbers. When the number is large and represented as strings we can process the number digit by digit. The main observation is that if the last digit of the number is ? 5 then only the last digit will get affected i.e. it will be replaced with a 0. If it is something greater than 5 then the number has to be rounded to some next higher multiple of 10 i.e. the last digit will be replaced with a 0 and 1 will have to be added to the rest of the number i.e. the number represented by the sub-string str[0…n-1] which can be done by storing carry generated at every step (digit).

Below is the implementation of the above approach: 

C++




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


Java




// Java implementation of the approach
import java.io.*;
class GFG
{
 
// Function to round the given number
// to the nearest multiple of 10
static void roundToNearest(StringBuilder str, int n)
{
 
    // If string is empty
    if (str.toString() == "")
        return;
 
    // If the last digit is less than or equal to 5
    // then it can be rounded to the nearest
    // (previous) multiple of 10 by just replacing
    // the last digit with 0
    if (str.charAt(n - 1) - '0' <= 5)
    {
 
        // Set the last digit to 0
        str.setCharAt(n - 1, '0');
 
        // Print the updated number
        System.out.print(str.substring(0, n));
    }
 
    // The number hast to be rounded to
    // the next multiple of 10
    else
    {
 
        // To store the carry
        int carry = 0;
 
        // Replace the last digit with 0
        str.setCharAt(n - 1, '0');
 
        // Starting from the second last digit,
        // add 1 to digits while there is carry
        int i = n - 2;
        carry = 1;
 
        // While there are digits to consider
        // and there is carry to add
        while (i >= 0 && carry == 1)
        {
 
            // Get the current digit
            int currentDigit = str.charAt(i) - '0';
 
            // Add the carry
            currentDigit += carry;
 
            // If the digit exceeds 9 then
            // the carry will be generated
            if (currentDigit > 9)
            {
                carry = 1;
                currentDigit = 0;
            }
 
            // Else there will be no carry
            else
                carry = 0;
 
            // Update the current digit
            str.setCharAt(i, (char)(currentDigit + '0'));
 
            // Get to the previous digit
            i--;
        }
 
        // If the carry is still 1 then it must be
        // inserted at the beginning of the string
        if (carry == 1)
            System.out.print(carry);
 
        // Print the rest of the number
        System.out.print(str.substring(0, n));
    }
}
 
// Driver code
public static void main(String[] args)
{
    StringBuilder str = new StringBuilder("99999999999999993");
    int n = str.length();
    roundToNearest(str, n);
}
}
 
// This code is contributed by
// sanjeev2552


Python3




# Python 3 implementation of the approach
 
# Function to round the given number
# to the nearest multiple of 10
def roundToNearest(str, n):
     
    # If string is empty
    if (str == ""):
        return
 
    # If the last digit is less than or equal to 5
    # then it can be rounded to the nearest
    # (previous) multiple of 10 by just replacing
    # the last digit with 0
    if (ord(str[n - 1]) - ord('0') <= 5):
         
        # Set the last digit to 0
        str = list(str)
        str[n - 1] = '0'
        str = ''.join(str)
 
        # Print the updated number
        print(str[0:n])
 
    # The number hast to be rounded to
    # the next multiple of 10
    else:
         
        # To store the carry
        carry = 0
 
        # Replace the last digit with 0
        str = list(str)
        str[n - 1] = '0'
 
        str = ''.join(str)
 
        # Starting from the second last digit,
        # add 1 to digits while there is carry
        i = n - 2
        carry = 1
 
        # While there are digits to consider
        # and there is carry to add
        while (i >= 0 and carry == 1):
             
            # Get the current digit
            currentDigit = ord(str[i]) - ord('0')
 
            # Add the carry
            currentDigit += carry
 
            # If the digit exceeds 9 then
            # the carry will be generated
            if (currentDigit > 9):
                carry = 1
                currentDigit = 0
 
            # Else there will be no carry
            else:
                carry = 0
 
            # Update the current digit
            str[i] = chr(currentDigit + '0')
 
            # Get to the previous digit
            i -= 1
 
        # If the carry is still 1 then it must be
        # inserted at the beginning of the string
        if (carry == 1):
            print(carry)
 
        # Print the rest of the number
        print(str[0:n])
     
# Driver code
if __name__ == '__main__':
    str = "99999999999999993"
    n = len(str)
 
    roundToNearest(str, n)
 
# This code is contributed by
# Surendra_Gangwar


C#




// C# implementation of the approach
using System;
using System.Text;
 
class GFG
{
 
// Function to round the given number
// to the nearest multiple of 10
static void roundToNearest(StringBuilder str, int n)
{
 
    // If string is empty
    if (str.ToString() == "")
        return;
 
    // If the last digit is less than or equal to 5
    // then it can be rounded to the nearest
    // (previous) multiple of 10 by just replacing
    // the last digit with 0
    if (str[n - 1] - '0' <= 5)
    {
 
        // Set the last digit to 0
        str[n - 1] = '0';
 
        // Print the updated number
        Console.Write(str.ToString().Substring(0, n));
    }
 
    // The number hast to be rounded to
    // the next multiple of 10
    else
    {
 
        // To store the carry
        int carry = 0;
 
        // Replace the last digit with 0
        str[n - 1] = '0';
 
        // Starting from the second last digit,
        // add 1 to digits while there is carry
        int i = n - 2;
        carry = 1;
 
        // While there are digits to consider
        // and there is carry to add
        while (i >= 0 && carry == 1)
        {
 
            // Get the current digit
            int currentDigit = str[i] - '0';
 
            // Add the carry
            currentDigit += carry;
 
            // If the digit exceeds 9 then
            // the carry will be generated
            if (currentDigit > 9)
            {
                carry = 1;
                currentDigit = 0;
            }
 
            // Else there will be no carry
            else
                carry = 0;
 
            // Update the current digit
            str[i] = (char)(currentDigit + '0');
 
            // Get to the previous digit
            i--;
        }
 
        // If the carry is still 1 then it must be
        // inserted at the beginning of the string
        if (carry == 1)
            Console.Write(carry);
 
        // Print the rest of the number
        Console.Write(str.ToString().Substring(0, n));
    }
}
 
// Driver code
public static void Main(String[] args)
{
    StringBuilder str = new StringBuilder("99999999999999993");
    int n = str.Length;
    roundToNearest(str, n);
}
}
 
// This code is contributed by
// Rajnis09


Javascript




// JS implementation of the approach
 
// Function to round the given number
// to the nearest multiple of 10
function roundToNearest(str, n)
{
    str = Array.from(str)
     
    // If string is empty
    if ((str.join("")).localeCompare("") == 0)
        return;
 
    // If the last digit is less than or equal to 5
    // then it can be rounded to the nearest
    // (previous) multiple of 10 by just replacing
    // the last digit with 0
    if (parseInt(str[n - 1]) <= 5)
    {
 
        // Set the last digit to 0
        str[n - 1] = '0';
 
        // Print the updated number
        process.stdout.write(str.join(""));
    }
 
    // The number hast to be rounded to
    // the next multiple of 10
    else
    {
 
        // To store the carry
        let carry = 0;
 
        // Replace the last digit with 0
        str[n - 1] = '0';
 
        // Starting from the second last digit,
        // add 1 to digits while there is carry
        let i = n - 2;
        carry = 1;
 
        // While there are digits to consider
        // and there is carry to add
        while (i >= 0 && carry == 1)
        {
 
            // Get the current digit
            let currentDigit = parseInt(str[i]);
 
            // Add the carry
            currentDigit += carry;
 
            // If the digit exceeds 9 then
            // the carry will be generated
            if (currentDigit > 9)
            {
                carry = 1;
                currentDigit = 0;
            }
 
            // Else there will be no carry
            else
                carry = 0;
 
            // Update the current digit
            str[i] = String(currentDigit);
 
            // Get to the previous digit
            i--;
        }
 
        // If the carry is still 1 then it must be
        // inserted at the beginning of the string
        if (carry == 1)
            process.stdout.write(1);
 
        // Print the rest of the number
        process.stdout.write(str.join(""));
    }
}
 
// Driver code
let str = "99999999999999993";
let n = str.length;
roundToNearest(str, n);
  
// This code is contributed by
// phasing17


Output:

99999999999999990

Time Complexity: O(n), where n is the length of the given string.
Auxiliary Space: O(1), no extra space is required, so it is a constant.

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments