简体   繁体   中英

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);
}

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);
}

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

将元素转换为字符串,然后为每个字符循环,将字符转换为int并将其加到上一个字符的总和。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM