Reputation: 13
I have trouble understanding how to replace all elements in vector by the sum of element digits. For example if i have sequence of such digits 9 22 54 981
my output has to be 9 4 9 18
.I know how to count the sum. I have this vector called file_numbers
.But I am stuck at this point. Thanks for the help.
int SumOfDigits(int digit)
{
int sum = 0;
while (digit > 0)
{
sum += digit % 10;
digit /= 10;
}
return sum;
}
void FourthTask(vector<int>& file_numbers)
{
std::transform(file_numbers.begin(),
file_numbers.end(),
file_numbers.begin(),SumOfDigits);
}
Upvotes: 1
Views: 429
Reputation: 425
Code first, then notes:
void SumTask(std::vector<int>& file_numbers){
for (auto& i : file_numbers){
int sum = 0;
while (i > 0){
sum += i % 10;
i /= 10;
}
i = sum;
}
}
Notes:
Upvotes: 0
Reputation: 77294
You might need to #include <algorithm>
int SumOfDigits(int digit)
{
int sum = 0;
while (digit > 0)
{
sum += digit % 10;
digit /= 10;
}
return sum;
}
void FourthTask(vector<int>& file_numbers)
{
std::transform(file_numbers.begin(),
file_numbers.end(),
file_numbers.begin(),
SumOfDigits);
}
Upvotes: 4
Reputation: 799
Convert the element to string, then loop for each character, convert character to int and add it up to previous character's sum..
Upvotes: -2