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

73 lines
1.6 KiB
C++
Raw Normal View History

2020-06-15 22:11:20 +05:30
/**
2020-06-15 23:17:50 +05:30
* Copyright 2020 @author iamnambiar
*
2020-06-15 23:17:50 +05:30
* @file
* \brief A C++ Program to find the Sum of Digits of input integer.
2020-06-15 22:11:20 +05:30
*/
2020-06-15 23:17:50 +05:30
#include <cassert>
#include <iostream>
2020-06-15 22:11:20 +05:30
/**
* Function to find the sum of the digits of an integer.
* @param num The integer.
* @return Sum of the digits of the integer.
*
2020-06-16 08:03:14 +05:30
* \detail
* First the algorithm check whether the num is negative or positive,
* if it is negative, then we neglect the negative sign.
* Next, the algorithm extract the last digit of num by dividing by 10
2020-06-16 08:03:14 +05:30
* and extracting the remainder and this is added to the sum.
* The number is then divided by 10 to remove the last digit.
* This loop continues until num becomes 0.
2020-06-15 22:11:20 +05:30
*/
int sum_of_digits(int num) {
2020-06-16 08:03:14 +05:30
// If num is negative then negative sign is neglected.
2020-06-15 23:17:50 +05:30
if (num < 0) {
num = -1 * num;
}
2020-06-15 22:11:20 +05:30
int sum = 0;
while (num > 0) {
sum = sum + (num % 10);
num = num / 10;
}
return sum;
}
2020-06-15 23:17:50 +05:30
/**
2020-06-16 08:03:14 +05:30
* Function for testing the sum_of_digits() function with a
* first test case of 119765 and assert statement.
2020-06-15 23:17:50 +05:30
*/
2020-06-16 08:03:14 +05:30
void test1() {
2020-06-15 23:17:50 +05:30
int test_case_1 = sum_of_digits(119765);
assert(test_case_1 == 29);
2020-06-18 11:04:27 +05:30
}
2020-06-16 08:03:14 +05:30
/**
* Function for testing the sum_of_digits() function with a
* second test case of -12256 and assert statement.
*/
void test2() {
int test_case_2 = sum_of_digits(-12256);
2020-06-15 23:17:50 +05:30
assert(test_case_2 == 16);
2020-06-18 11:04:27 +05:30
}
2020-06-16 08:03:14 +05:30
/**
* Function for testing the sum_of_digits() with
2020-06-16 08:03:14 +05:30
* all the test cases.
*/
void test() {
2020-06-16 08:05:06 +05:30
// First test.
2020-06-16 08:03:14 +05:30
test1();
2020-06-16 08:05:06 +05:30
// Second test.
2020-06-16 08:03:14 +05:30
test2();
2020-06-18 11:04:27 +05:30
}
2020-06-15 23:17:50 +05:30
2020-06-16 08:03:14 +05:30
/**
* Main Function
*/
2020-06-15 23:17:50 +05:30
int main() {
test();
2020-06-16 08:03:14 +05:30
std::cout << "Success." << std::endl;
2020-06-15 22:11:20 +05:30
return 0;
2020-06-15 23:17:50 +05:30
}