Digits of the number
The need to use the operation of calculating the remainder of the division is visible when working with digits of the number.
Problem:
Given an three-digit number. Output all the digits of the number on the screen and get a new number formed by a by the interchanging the digits of ones and hundreds.
The most difficult question that newcomers have is how to get the numbers from a number. In fact, it is quite simple, if you remember the math. And mathematics tells us that any number can be decomposed into a sum of digit summation terms.
Example
365 = 3*100 + 6*10 + 5*1
.
- Select and save all digits of the number in separate variables.
e = n % 10; // operator n % 10 - ones of the number n 365 % 10 = 5
d = n / 10 % 10; // operator n / 10 - calculate the number by 10 times,
// that is, it discards the last digit from the number (365 / 10 = 36),
// now we can calculate the number of tens
// by applying the familiar operation to the result -
// calculate the remainder of the division by 10, 36 % 10 = 6
s = n / 100; // to get hundreds, it’s enough to discard two digits
// from the number on the right, that is, divide twice by 10
// (n / 10 / 10 or n / 100) 365 / 100 = 3
- Having the saved digits of a number, we can make any number from them, multiplying the desired digit by the corresponding digit:
For example, the line below will get a new number from the original number
n
, which has hundreds and ones interchanging:
1) the old number of units (stored in variable
e
) is multiplied by 100
2) the old number of tens (stored in the variable
d
) is multiplied by 10
3) we can multiply the old number of hundreds simply by 1, or simply take the value stored in the variable
s.
Then the values from points 1, 2 and 3 are simply added up and we get a new number:
n1 = e * 100 + d * 10 + s;
Implementation
#include <iostream>
using namespace std;
int main()
{
int n, e, d, s;
cin >> n;
e = n % 10;
d = n / 10 % 10;
s = n / 100;
cout << e << " " << d << " " << s << " " << e * 100 + d * 10 + s << endl;
return 0;
}