mirror of
https://github.com/TheAlgorithms/C-Plus-Plus.git
synced 2026-04-01 17:52:40 +08:00
fix: sum of digits bug
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user