Maximum and Minimum Digit in a Number

Problem Statement: Given a number N, print the smallest and largest digits present in the number.

Examples:

Example 1:
Input: N = 2746
Output: Largest digit: 7
        Smallest digit: 2
Explanation: By simply going through the digits of 
the number, we figure out the largest and smallest 
digit in the number.

Example 2:
Input: N = 23004
Output: Largest digit : 4
        Smallest digit : 0
Explanation: By simply going through the digits of 
the number, we figure out the largest and smallest 
digit in the number.

Solution:

DisclaimerDon’t jump directly to the solution, try it out yourself first.

Intuition: The first thing that comes to our mind is to go through individual digits of the number and update the maximum and minimum digits that we come across. Notice, how this problem resembles the pattern of the sum of digits, reversing of digits in a number. All these questions come under the same format of extracting the digits, doing some calculations, and coming up with an answer.

Approach : 

  • Get every digit of the number using the modulus operator
  • Update the max and min digit on the go and repeat the process until the number is not zero
  • Here’s a quick demonstration of the same

Code:

C++ Code

#include<bits/stdc++.h>
using namespace std;
void MinMax(int n)
{
    int d,mini=INT_MAX,maxi=INT_MIN;
    while(n!=0)
    {
        d=n%10;
        mini = min(mini,d);
        maxi=max(maxi,d);
        n=n/10;
    }
    
    cout<<"The minimum number is: "<<mini<<"\n"
        <<"The maximum number is: "<<maxi;
}

int main()
{
    int n = 4726;
    MinMax(n);
    return 0;
}

Output:

The minimum number is: 2
The maximum number is: 7

Time Complexity: O(log N)

Space Complexity: O(1)

Java Code

import java.io.*;
class Test
{
static private void MinMax(int n)
{
	int d;
	int mini = Integer.MAX_VALUE;
	int maxi = Integer.MIN_VALUE;
	while (n != 0)
	{
		d = n % 10;
		mini = Math.min(mini,d);
		maxi = Math.max(maxi,d);
		n = n / 10;
	}

	System.out.println("The minimum number is: "+mini);
	System.out.print("The maximum number is: "+maxi);
}
public static void main(String[] args)
{
	int n = 4726;
	MinMax(n);
}
}

Output:

The minimum number is: 2
The maximum number is: 7

Time Complexity: O(log N)

Space Complexity: O(1)

Special thanks to Naman Daga for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article