A string s is given to represent a positive number. The task is to round s to the nearest multiple of 10. If you have two multiples equally apart from s, choose the smallest element among them.
Examples:
Input: s = "29"
Output: 30
Explanation: Close multiples are 20 and 30, and 30 is the nearest to 29.
Input: s = "15"
Output: 10
Explanation: 10 and 20 are equally distant multiples from 20. The smallest of the two is 10.
Table of Content
[Naive Approach] Try Both Nearby Multiples - O(n) Time and O(1) Space
The idea is to find the two nearest multiples of 10 and return the one having the minimum difference. If both are equally distant, return the smaller multiple.
#include <iostream>
#include <string>
using namespace std;
string roundToNearest(string &s)
{
// Convert string to number
int num = stoll(s);
// Find lower and upper multiples of 10
int lower = (num / 10) * 10;
int upper = lower + 10;
// Find distance from both multiples
int diffLower = num - lower;
int diffUpper = upper - num;
// If lower is closer or both are equal,
// return lower multiple
if (diffLower <= diffUpper)
return to_string(lower);
// Otherwise return upper multiple
return to_string(upper);
}
int main()
{
string s = "29";
cout << roundToNearest(s);
return 0;
}
import java.util.*;
public class Main {
// Convert string to number
static String roundToNearest(String s) {
int num = Integer.parseInt(s);
// Find lower and upper multiples of 10
int lower = (num / 10) * 10;
int upper = lower + 10;
// Find distance from both multiples
int diffLower = num - lower;
int diffUpper = upper - num;
// If lower is closer or both are equal,
// return lower multiple
if (diffLower <= diffUpper)
return Integer.toString(lower);
// Otherwise return upper multiple
return Integer.toString(upper);
}
public static void main(String[] args) {
String s = "29";
System.out.println(roundToNearest(s));
}
}
"""
Convert string to number
"""
def roundToNearest(s):
num = int(s)
# Find lower and upper multiples of 10
lower = (num // 10) * 10
upper = lower + 10
# Find distance from both multiples
diffLower = num - lower
diffUpper = upper - num
# If lower is closer or both are equal,
# return lower multiple
if diffLower <= diffUpper:
return str(lower)
# Otherwise return upper multiple
return str(upper)
if __name__ == '__main__':
s = "29"
print(roundToNearest(s))
using System;
class Program {
// Convert string to number
static string roundToNearest(string s) {
int num = Int32.Parse(s);
// Find lower and upper multiples of 10
int lower = (num / 10) * 10;
int upper = lower + 10;
// Find distance from both multiples
int diffLower = num - lower;
int diffUpper = upper - num;
// If lower is closer or both are equal,
// return lower multiple
if (diffLower <= diffUpper)
return lower.ToString();
// Otherwise return upper multiple
return upper.ToString();
}
static void Main() {
string s = "29";
Console.WriteLine(roundToNearest(s));
}
}
// Convert string to number
function roundToNearest(s) {
let num = parseInt(s, 10);
// Find lower and upper multiples of 10
let lower = Math.floor(num / 10) * 10;
let upper = lower + 10;
// Find distance from both multiples
let diffLower = num - lower;
let diffUpper = upper - num;
// If lower is closer or both are equal,
// return lower multiple
if (diffLower <= diffUpper)
return lower.toString();
// Otherwise return upper multiple
return upper.toString();
}
let s = "29";
console.log(roundToNearest(s));
Output
30
[Expected Approach] Rounding Using Last Digit and Carry Handling - O(n) Time and O(1) Space
The idea is to use the last digit of the number. If it is 0-5, replace it with 0; otherwise replace it with 0 and add 1 to the previous digits using carry handling.
Let us understand with an example:
- For s = "29", the last digit is 9, which is greater than 5, so we round up.
- Replace the last digit with 0: 29 → 20.
- Add 1 to the previous digits: 2 + 1 = 3.
- The final rounded number becomes 30.
- Return 30 as the answer.
#include <iostream>
#include <string>
using namespace std;
string roundToNearest(string &s)
{
int n = s.size();
// 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
if (s[n - 1] - '0' <= 5)
{
// Set the last digit to 0
s[n - 1] = '0';
// Print the updated number
return s.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
s[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 = s[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
s[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;
// Prin the rest of the number
return s.substr(0, n);
}
}
int main()
{
string s = "29";
cout << roundToNearest(s);
return 0;
}
public class Main {
public static String roundToNearest(String s) {
int n = s.length();
// 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
if (s.charAt(n - 1) - '0' <= 5) {
// Set the last digit to 0
s = s.substring(0, n - 1) + '0';
// Return the updated number
return s;
}
// 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
s = s.substring(0, 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 = s.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
s = s.substring(0, i) + (char)(currentDigit + '0') + s.substring(i + 1);
// 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)
s = "1" + s;
// Return the rest of the number
return s;
}
}
public static void main(String[] args) {
String s = "29";
System.out.println(roundToNearest(s));
}
}
def roundToNearest(s):
n = len(s)
# 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
if int(s[n - 1]) <= 5:
# Set the last digit to 0
s = s[:n - 1] + '0'
# Return the updated number
return s
# 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
s = s[:n - 1] + '0'
# 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 = int(s[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:
carry = 0
# Update the current digit
s = s[:i] + str(currentDigit) + s[i + 1:]
# 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:
s = '1' + s
# Return the rest of the number
return s
if __name__ == '__main__':
s = "29"
print(roundToNearest(s))
using System;
class Program
{
static string roundToNearest(string s)
{
int n = s.Length;
// 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
if (s[n - 1] - '0' <= 5)
{
// Set the last digit to 0
s = s.Substring(0, n - 1) + '0';
// Return the updated number
return s;
}
// 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
s = s.Substring(0, 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 = s[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
s = s.Substring(0, i) + (char)(currentDigit + '0') + s.Substring(i + 1);
// 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)
s = "1" + s;
// Return the rest of the number
return s;
}
}
static void Main()
{
string s = "29";
Console.WriteLine(roundToNearest(s));
}
}
Output
30