Ter Rini
Ter Rini

Reputation: 13

How to replace all elements in vector by the sum of element digits?

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

Answers (3)

Alex Shirley
Alex Shirley

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:

  • Sum goes inside the for loop, otherwise you're going to sum all the digits previously processed as well
  • Use a range-loop, they're pretty well optimized

Upvotes: 0

nvoigt
nvoigt

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

Merak Marey
Merak Marey

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

Related Questions