TheAlgorithms-C-Plus-Plus/math/sum_of_digits.cpp

42 lines
763 B
C++
Raw Normal View History

2020-06-16 00:41:20 +08:00
/**
2020-06-16 01:47:50 +08:00
* Copyright 2020 @author iamnambiar
*
* @file
* A C++ Program to find the Sum of Digits of input integer.
2020-06-16 00:41:20 +08:00
*/
#include <iostream>
2020-06-16 01:47:50 +08:00
#include <cassert>
2020-06-16 00:41:20 +08:00
/**
* 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) {
2020-06-16 01:47:50 +08:00
if (num < 0) {
num = -1 * num;
}
2020-06-16 00:41:20 +08:00
int sum = 0;
while (num > 0) {
sum = sum + (num % 10);
num = num / 10;
}
return sum;
}
2020-06-16 01:47:50 +08:00
/**
* Test function.
*/
2020-06-16 01:56:58 +08:00
void test() {
2020-06-16 01:47:50 +08:00
int test_case_1 = sum_of_digits(119765);
int test_case_2 = sum_of_digits(-12256);
assert(test_case_1 == 29);
assert(test_case_2 == 16);
2020-06-16 00:41:20 +08:00
}
2020-06-16 01:47:50 +08:00
int main() {
test();
std::cout << "Success.";
2020-06-16 00:41:20 +08:00
return 0;
2020-06-16 01:47:50 +08:00
}