Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Natural Numbers
  • Whole Numbers
  • Real Numbers
  • Integers
  • Rational Numbers
  • Irrational Numbers
  • Complex Numbers
  • Prime Numbers
  • Odd Numbers
  • Even Numbers
  • Properties of Numbers
  • Number System
Open In App
Next Article:
C++ Program for Smallest K digit number divisible by X
Next article icon

Largest and smallest digit of a number

Last Updated : 13 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
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)



Next Article
C++ Program for Smallest K digit number divisible by X
author
ritikadhamija
Improve
Article Tags :
  • C++ Programs
  • DSA
  • Mathematical
  • number-digits
  • Numbers
  • school-programming
Practice Tags :
  • Mathematical
  • Numbers

Similar Reads

  • Find longest length number in a string
    Given a string of digits and characters. Write a program to find the number with the maximum number of digits in a string. Note: The number may not be the greatest number in the string. For example, if the string is "a123bc321" then the answer can be 123 or 321 as the problem is to find the number w
    6 min read
  • C++ Program for Smallest K digit number divisible by X
    Integers X and K are given. The task is to find the smallest K-digit number divisible by X. Examples: Input : X = 83, K = 5 Output : 10043 10040 is the smallest 5 digit number that is multiple of 83. Input : X = 5, K = 2 Output : 10 An efficient solution would be : Compute MIN : smallest K-digit num
    2 min read
  • How to Find Largest Number in an Array in C++?
    In C++, arrays are used to store the collection of similar elements to be stored in adjacent memory locations. They can store data of any type such as int, char, float, etc. In this article, we will learn how to find the largest number in an array in C++. For Example,Input: myVector = {1, 3, 10, 7,
    2 min read
  • C++ Program for Largest K digit number divisible by X
    Integers X and K are given. The task is to find highest K-digit number divisible by X. Examples: Input : X = 30, K = 3 Output : 990 990 is the largest three digit number divisible by 30. Input : X = 7, K = 2 Output : 98 An efficient solution is to use below formula. ans = MAX - (MAX % X) where MAX i
    1 min read
  • How to Find the Smallest Number in an Array in C++?
    In C++, arrays are the data types that store the collection of the elements of other data types such as int, float, etc. In this article, we will learn how to find the smallest number in an array using C++. For Example,Input: myVector = {10, 3, 10, 7, 1, 5, 4} Output: Smallest Number = 1Find the Sma
    2 min read
  • Smallest number greater than or equal to N using only digits 1 to K
    Given a number N and an integer K, the task is to find the smallest number greater than or equal to N, formed using only first K non-zero digits( 1, 2, ..., K-1, K).Examples: Input: N = 124, K = 3 Output: 131 Explanation: The smallest number greater than or equal to 124, which is only made of digits
    9 min read
  • Maximum value of long long int in C++
    In this article, we will discuss the long long int data type in C++. long long int data type in C++ is used to store 64-bit integers. It is one of the largest data types to store integer values, unlike unsigned long long int both positive and negative. Some properties of the long long int data type
    2 min read
  • Maximum number with same digit factorial product
    Given a string str which represents an integer, the task is to find the largest number without any leading or trailing zeros or ones whose product of the factorial of its digits is equal to the product of the factorial of digits of str.Examples: Input: N = 4370 Output: 73322 4! * 3! * 7! * 0! = 7! *
    10 min read
  • C++ Program to Find Largest Element in an Array
    In this article, we will learn to write a C++ program to find the largest element in the given array arr of size N. The element that is greater than all other elements is the largest element in the array. Recommended PracticeHelp a Thief!!!Try It! One of the most simplest and basic approaches to fin
    2 min read
  • C++ Program to Find Maximum value possible by rotating digits of a given number
    Given a positive integer N, the task is to find the maximum value among all the rotations of the digits of the integer N. Examples: Input: N = 657Output: 765Explanation: All rotations of 657 are {657, 576, 765}. The maximum value among all these rotations is 765. Input: N = 7092Output: 9270Explanati
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences