

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program to find the smallest digit in a given number
Given a non-negative number, the task is to find its smallest digit.
For example
Input:
N = 154870
Output:
0
Explanation: In the given number '154870', the smallest digit is '0'.
Approach to Solve this Problem
The simplest approach to solve this problem is to extract the last digit in the given number using the remainder theorem. While traversing the number, we will check if the extracted digit is less than the last digit, then return the output.
- Take a number n as the input.
- An integer function smallest_digit(int n) takes 'n' as the input and returns the smallest digit in the given number.
- Now initialize min as the last digit of the given number.
- Iterate through the number and check if the number extracted is less than the minimum number. If true, then update the minimum number and return the output.
- Remove the last digit by n/10 and check if there is another digit which is lesser than the current digit.
- Return the output.
Example
#include <iostream> using namespace std; int smallest_digit(int n) { int min = n % 10; //assume that last digit is the smallest n /= 10; //to start from the second last digit while (n != 0) { if (min > n % 10) min = n % 10; n /= 10; } return min; } int main() { int n = 154870; cout << smallest_digit(n); return 0; }
Running the above code will generate the output as,
Output
0
Explanation: In the given number '154870', the smallest digit is '0'.
- Related Questions & Answers
- JavaScript - Find the smallest n digit number or greater
- Find smallest permutation of given number in C++
- C++ Program for Smallest K digit number divisible by X?
- Program to find nth smallest number from a given matrix in Python
- 8085 Program to find the smallest number
- C++ program to find number in given range where each digit is distinct
- Python program to find the smallest number in a list
- Find the Smallest Divisor Given a Threshold in C++
- C++ program to find first digit in factorial of a number
- Write a C program to find out the largest and smallest number in a series
- Python Program for Smallest K digit number divisible by X
- Java Program for Smallest K digit number divisible by X
- Program to find super digit of a number in Python
- Java program to find the smallest number in an array
- C program to find sum of digits of a five digit number
Advertisements