Grade 9 · Digits of a numberCitește în română
Largest and smallest digit
Original: Cifra maximă și cifra minimă
O(n)C++1739 lines1 example
The idea
We start with the maximum at 0 (the smallest possible digit) and the minimum at 9 (the largest possible digit), then compare every digit with them. We use do-while so that n = 0 has maximum and minimum 0.
Original description (Romanian)
Pornim cu maximul 0 (cea mai mică cifră posibilă) și minimul 9 (cea mai mare cifră posibilă), apoi comparăm fiecare cifră cu ele. Folosim do-while pentru ca n = 0 să aibă maximul și minimul 0.
- Complexity
- O(k), where k is the number of digits of n
- Grade
- Grade 9 (Clasa a IX-a)
- Chapter
- Digits of a number
Examples
Example 1
Input
52918
Expected output
9 1
The code
Comments are in Romanian, as in the original collection. Edit freely: you can reset at any time.
/*
* Titlu: Cifra maximă și cifra minimă
* Clasa: 9
* Capitol: Cifrele unui număr
* Descriere: Pornim cu maximul 0 (cea mai mică cifră posibilă) și minimul 9
* (cea mai mare cifră posibilă), apoi comparăm fiecare cifră cu ele.
* Folosim do-while pentru ca n = 0 să aibă maximul și minimul 0.
* Complexitate: O(k), unde k este numărul de cifre ale lui n
*
* Exemplu
* Intrare: 52918
* Ieșire: 9 1
*/
#include <iostream>
using namespace std;
int main()
{
long long n;
int cifraMax = 0, cifraMin = 9;
cin >> n;
do
{
int cifra = n % 10;
if (cifra > cifraMax)
{
cifraMax = cifra;
}
if (cifra < cifraMin)
{
cifraMin = cifra;
}
n = n / 10;
}
while (n > 0);
cout << cifraMax << ' ' << cifraMin << '\n';
return 0;
}
Runs on a real g++ (C++17, -O2) through Compiler Explorer. Keep runs short; there's a time limit.