fix: sum of digits bug

This commit is contained in:
Neeraj C
2020-06-15 23:17:50 +05:30
parent de4578c1a4
commit d86a9b56df

View File

@@ -1,7 +1,11 @@
/**
* A simple C++ Program to find the Sum of Digits of input integer.
* Copyright 2020 @author iamnambiar
*
* @file
* A C++ Program to find the Sum of Digits of input integer.
*/
#include <iostream>
#include <cassert>
/**
* Function to find the sum of the digits of an integer.
@@ -9,6 +13,9 @@
* @return Sum of the digits of the integer.
*/
int sum_of_digits(int num) {
if (num < 0) {
num = -1 * num;
}
int sum = 0;
while (num > 0) {
sum = sum + (num % 10);
@@ -17,12 +24,18 @@ int sum_of_digits(int num) {
return sum;
}
int main() {
int num;
std::cin >> num;
if (num < 0) {
num = -1 * num;
/**
* Test function.
*/
void test() {
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);
}
std::cout << sum_of_digits(num);
int main() {
test();
std::cout << "Success.";
return 0;
}
}