Write a program to find the sum of the digits of a given integer N.
Solving this problem is easy manually if the number is given to you on paper: you simply see the digits written down and you can add them up. A computer program does not “see” the digits. However, you can get the least significant digit by taking the remainder modulo 10, using the % operator. You can determine the number resulting from erasing the least significant digit of an integer x by dividing x by 10. As you know x/10 will equal the quotient, which is exactly what remains if you erase the last digit of x. If you now take the remainder of this modulo 10 you will get the second least significant digit. Thus by alternately taking the remainder modulo 10 and dividing by 10 you will be able to obtain the different digits. So then you can add them up. All that remains is to put this into a nice loop.
INPUT:
N (1<=N<=1000000000). The upper bound for N is set at 109 so that the numbers will fit in standard int.
OUTPUT:
Sum of digits of N.
SOLUTION:
int main() { int N, s = 0; cin >> N; if (N <= 0 || N >= 1000000000) { exit(0); } else { while (N != 0) { s = s + N % 10; N = N / 10; } cout << s << endl; } return 0; }
Comments
Post a Comment