Introduce
Today, let us learn C++'s general digital separation algorithm together. This is a very simple to use method, which can be used for a series of problems, such as sum, palindrome number and so on. Now, let's solve the sum of digits for general digit separation.
Example presentation
Enter a number n, and find the sum of the digits of the numbers 1-n. (The range of n is between 1-9999999)
Example analysis
The range of n is 7 digits, so the type is long long; because the value of n is input, it cannot be determined. It must not be separated by one bit like flashback inputting three digits. At this time, use To complete this operation on the universal digital separation, let us first look at how to use the universal digital separation
Universal digital separation
The specific procedures are as follows:
p = x;
do{
a = p % 10;
p = p / 10;
}while(p>0);
}
Looking at the program, we can see that this algorithm is separated by one bit from the end.
If the input is 123: the first time a is 3; the second time a is 2; the third time a is 1.
Sample program
The sample program is as follows:
#include <iostream>
using namespace std;
int main(){
int n;
cin >> n;
int p=n;
int sum=0;
int(int i=1; i<=n; i++){
do{
sum += p % 10;
p = p / 10;
}while(p>0);
}
cout << sum;
return 0;
}