Open In App
Related Articles

Largest and smallest digit of a number

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Given a number N. The task is to find the largest and the smallest digit of the number.
Examples :

Input : N = 2346 
Output : 6 2 
6 is the largest digit and 2 is smallest
Input : N = 5 
Output : 5 5

Approach: An efficient approach is to find all digits in the given number and find the largest and the smallest digit. 

C++

// CPP program to largest and smallest digit of a number
#include <bits/stdc++.h>
using namespace std;
  
// Function to the largest and smallest digit of a number
void Digits(int n)
{
    int largest = 0;
    int smallest = 9;
  
    while (n) {
        int r = n % 10;
  
        // Find the largest digit
        largest = max(r, largest);
  
        // Find the smallest digit
        smallest = min(r, smallest);
  
        n = n / 10;
    }
    cout << largest << " " << smallest;
}
  
// Driver code
int main()
{
    int n = 2346;
  
    // Function call
    Digits(n);
  
    return 0;
}

                    

Java

// Java program to largest and smallest digit of a number
import java.util.*;
import java.lang.*;
import java.io.*;
  
class Gfg
{
      
// Function to the largest and smallest digit of a number
static void Digits(int n)
{
    int largest = 0;
    int smallest = 9;
  
    while(n != 0
    {
        int r = n % 10;
  
        // Find the largest digit
        largest = Math.max(r, largest);
  
        // Find the smallest digit
        smallest = Math.min(r, smallest);
  
        n = n / 10;
    }
    System.out.println(largest + " " + smallest);
}
  
// Driver code
public static void main (String[] args) throws java.lang.Exception
{
    int n = 2346;
  
    // Function call
    Digits(n);
  
}
}
  
// This code is contributed by nidhiva

                    

Python3

# Python3 program to largest and smallest digit of a number
  
# Function to the largest and smallest digit of a number
def Digits(n):
    largest = 0
    smallest = 9
  
    while (n):
        r = n % 10
  
        # Find the largest digit
        largest = max(r, largest)
  
        # Find the smallest digit
        smallest = min(r, smallest)
  
        n = n // 10
  
    print(largest,smallest)
  
  
# Driver code
  
n = 2346
  
# Function call
Digits(n)
  
# This code is contributed by mohit kumar 29

                    

C#

// C# program to largest and
// smallest digit of a number
using System;
      
class GFG
{
      
// Function to the largest and 
// smallest digit of a number
static void Digits(int n)
{
    int largest = 0;
    int smallest = 9;
  
    while(n != 0) 
    {
        int r = n % 10;
  
        // Find the largest digit
        largest = Math.Max(r, largest);
  
        // Find the smallest digit
        smallest = Math.Min(r, smallest);
  
        n = n / 10;
    }
    Console.WriteLine(largest + " " + smallest);
}
  
// Driver code
public static void Main (String[] args)
{
    int n = 2346;
  
    // Function call
    Digits(n);
}
}
  
// This code is contributed by PrinciRaj1992 

                    

Javascript

<script>
  
// Javascript program to largest and
// smallest digit of a number
  
// Function to the largest and smallest
// digit of a number
function Digits(n)
{
    let largest = 0;
    let smallest = 9;
  
    while (n) {
        let r = n % 10;
  
        // Find the largest digit
        largest = Math.max(r, largest);
  
        // Find the smallest digit
        smallest = Math.min(r, smallest);
  
        n = parseInt(n / 10);
    }
    document.write(largest + " " + smallest);
}
  
// Driver code
    let n = 2346;
  
    // Function call
    Digits(n);
  
</script>

                    

Output
6 2






Time Complexity: O(log(n)), where n is the given number
Auxiliary Space: O(1)

Approach : Using str(),min(),max()

C++

// C++ program to largest and smallest digit of a number
#include <bits/stdc++.h>
using namespace std;
  
// Function to the largest and smallest digit of a number
int main()
{
    int n = 2346;
    string s = to_string(n);
    cout << *(max_element(s.begin(), s.end())) << " ";
    cout << *(min_element(s.begin(), s.end())) << endl;
}
  
// This code is contributed by phasing17

                    

Java

// Java program to largest and smallest digit of a number
import java.util.stream.Collectors.*;
import java.util.stream.*;
import java.util.*;
  
class GFG
{
    
  // Function to the largest and smallest digit of a number
  public static void main(String[] args)
  {
    int n = 2346;
    String s1 = String.valueOf(n);
    List<Character> s = s1.chars().mapToObj(c -> (char) c).collect(Collectors.toList());
  
    Comparator<Character> comparator = Comparator.comparing( Character::valueOf );
  
    Character mins = s.stream().min(comparator).get();
    Character maxs = s.stream().max(comparator).get(); 
  
    System.out.println(maxs + " " + mins);
  }
}
  
// This code is contributed by phasing17

                    

Python3

# Python3 program to largest and smallest digit of a number
  
# Function to the largest and smallest digit of a number
n=2346
s=str(n)
print(max(s),end=" ")
print(min(s))

                    

C#

// C# program to largest and smallest digit of a number
using System;
using System.Linq;
using System.Collections.Generic;
  
class GFG
{
    // Function to the largest and smallest digit of a number
    public static void Main(string[] args)
    {
        int n = 2346;
        char[] s = Convert.ToString(n).ToCharArray();
          
        Console.WriteLine(s.Max() + " " + s.Min());
    }
}
  
// This code is contributed by phasing17

                    

Javascript

// JS program to largest and smallest digit of a number
  
// Function to the largest and smallest digit of a number
let n=2346
let s = ("" + n).split("")
  
console.log(s[s.length - 1])
console.log(s[0])
  
  
// This code is contributed by phasing17

                    

Output
6 2






Time Complexity: O(1)

Auxiliary Space: O(1)

Approach#4: Using reduce

Convert the input number to a list of integers (digits). Use the reduce function to apply a lambda function that compares two digits at a time and returns the smallest or largest.

Algorithm

1. Convert the input number to a list of integers using map and list.
2. Use reduce function from functools module to find the smallest and largest digit.
3. In the lambda function passed to reduce, the two arguments x and y represent two adjacent digits in the list. The lambda function compares these two digits and returns the smallest or largest based on the condition.
4. The reduce function applies this lambda function to the entire list of digits, returning the smallest and largest digit.

C++

#include <algorithm>
#include <iostream>
#include <numeric> // Include this header for the accumulate function
#include <vector>
  
int main()
{
    std::string n = "2346";
    std::vector<int> digits;
  
    // Convert string to a vector of integers
    for (char c : n) {
        digits.push_back(c - '0');
    }
  
    // Find the smallest and largest digits using the
    // accumulate function
    int smallest = std::accumulate(
        digits.begin(), digits.end(), digits[0],
        [](int x, int y) { return std::min(x, y); });
  
    int largest = std::accumulate(
        digits.begin(), digits.end(), digits[0],
        [](int x, int y) { return std::max(x, y); });
  
    // Print the smallest and largest digits
    std::cout << "Smallest digit: " << smallest
              << std::endl;
    std::cout << "Largest digit: " << largest << std::endl;
  
    return 0;
}

                    

Java

import java.util.ArrayList;
import java.util.List;
  
public class Main {
    public static void main(String[] args) {
        String n = "2346";
        List<Integer> digits = new ArrayList<>();
  
        // Convert string to a list of integers
        for (char c : n.toCharArray()) {
            digits.add(Character.getNumericValue(c));
        }
  
        // Find the smallest and largest digits using the accumulate function
        int smallest = digits.stream().reduce(digits.get(0), Integer::min);
        int largest = digits.stream().reduce(digits.get(0), Integer::max);
  
        // Print the smallest and largest digits
        System.out.println("Smallest digit: " + smallest);
        System.out.println("Largest digit: " + largest);
    }
}

                    

Python3

from functools import reduce
  
n = '2346'
digits = list(map(int, n))
smallest = reduce(lambda x, y: x if x < y else y, digits)
largest = reduce(lambda x, y: x if x > y else y, digits)
  
print("Smallest digit:", smallest)
print("Largest digit:", largest)

                    

C#

using System;
using System.Linq;
  
class GFG
{
    static void Main()
    {
        string n = "2346";
          
        // Convert string to a List of integers
        var digits = n.Select(c => c - '0').ToList();
  
        // Find the smallest and largest digits using the
        // Aggregate function
        int smallest = digits.Aggregate((x, y) => Math.Min(x, y));
        int largest = digits.Aggregate((x, y) => Math.Max(x, y));
  
        // Print the smallest and largest digits
        Console.WriteLine("Smallest digit: " + smallest);
        Console.WriteLine("Largest digit: " + largest);
    }
}

                    

Javascript

// Define the input string
const n = "2346";
const digits = [];
  
// Convert string to an array of integers
for (const c of n) {
    digits.push(parseInt(c));
}
  
// Find the smallest and largest digits using the reduce function
const smallest = digits.reduce((x, y) => Math.min(x, y), digits[0]);
const largest = digits.reduce((x, y) => Math.max(x, y), digits[0]);
  
// Print the smallest and largest digits
console.log("Smallest digit: " + smallest);
console.log("Largest digit: " + largest);

                    

Output
Smallest digit: 2
Largest digit: 6






Time complexity: O(n)
Auxiliary Space: O(n)



Last Updated : 13 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads