Grade 9 · Digits of a numberCitește în română
Reverse of a number
Original: Oglinditul unui număr
O(n)C++1734 lines2 examples
The idea
Builds the number made of the digits of n written in reverse order. At every step we take the last digit (n % 10), append it to the right of the reversed number (ogl * 10 + digit) and cut it off n (n / 10).
Original description (Romanian)
Construiește numărul format din cifrele lui n scrise în ordine inversă. La fiecare pas luăm ultima cifră (n % 10), o lipim la dreapta oglinditului (ogl * 10 + cifra) și o tăiem din n (n / 10).
- 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
2134
Expected output
4312
Example 2
Input
1200
Expected output
21
The code
Comments are in Romanian, as in the original collection. Edit freely: you can reset at any time.
/*
* Titlu: Oglinditul unui număr
* Clasa: 9
* Capitol: Cifrele unui număr
* Descriere: Construiește numărul format din cifrele lui n scrise în ordine inversă.
* La fiecare pas luăm ultima cifră (n % 10), o lipim la dreapta
* oglinditului (ogl * 10 + cifra) și o tăiem din n (n / 10).
* Complexitate: O(k), unde k este numărul de cifre ale lui n
*
* Exemplu
* Intrare: 2134
* Ieșire: 4312
*
* Exemplu
* Intrare: 1200
* Ieșire: 21
*/
#include <iostream>
using namespace std;
int main()
{
long long n, ogl = 0;
cin >> n;
while (n > 0)
{
int cifra = n % 10;
ogl = ogl * 10 + cifra;
n = n / 10;
}
cout << ogl << '\n';
return 0;
}
Runs on a real g++ (C++17, -O2) through Compiler Explorer. Keep runs short; there's a time limit.