mirror of
https://hub.njuu.cf/TheAlgorithms/C-Plus-Plus.git
synced 2023-10-11 13:05:55 +08:00
feat: add sum of digits
This commit is contained in:
parent
70a2aeedc3
commit
de4578c1a4
28
math/sum_of_digits.cpp
Normal file
28
math/sum_of_digits.cpp
Normal file
@ -0,0 +1,28 @@
|
||||
/**
|
||||
* A simple C++ Program to find the Sum of Digits of input integer.
|
||||
*/
|
||||
#include <iostream>
|
||||
|
||||
/**
|
||||
* Function to find the sum of the digits of an integer.
|
||||
* @param num The integer.
|
||||
* @return Sum of the digits of the integer.
|
||||
*/
|
||||
int sum_of_digits(int num) {
|
||||
int sum = 0;
|
||||
while (num > 0) {
|
||||
sum = sum + (num % 10);
|
||||
num = num / 10;
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
int main() {
|
||||
int num;
|
||||
std::cin >> num;
|
||||
if (num < 0) {
|
||||
num = -1 * num;
|
||||
}
|
||||
std::cout << sum_of_digits(num);
|
||||
return 0;
|
||||
}
|
Loading…
Reference in New Issue
Block a user