您至少可以通过两种方式使其更通用:
- 只需为一个号码编写代码。
然后循环输入任何数字。
- 编写代码以添加任何
ith 数字。
因此,在这种情况下,您可以只关注如何提取给定数字 n 的 ith 数字。
如您的代码所示,可以使用(n / divisor) % 10 完成什么,其中divisor 将是exp(10, i),i 从0 开始。
Demo
#include <algorithm> // for_each
#include <iostream> // cout
#include <numeric> // accumulate
#include <vector>
int main()
{
std::vector<int> v{123'456, 99'999, 100};
auto sum_of_ith_digit = [](const std::vector<int>& v, size_t i) {
auto divisor{1};
while (i != 0) { divisor *= 10; i--; } // 1 for digit 0, 10 for digit 1, 100 for digit 2...
return std::accumulate(std::cbegin(v), std::cend(v), 0, // for each number in v
[&divisor](auto& total, const auto& n){ // get ith digit
return total + (n / divisor) % 10; // and add it to a total,
}); // then return the total
};
auto units = sum_of_ith_digit(v, 0);
auto tens = sum_of_ith_digit(v, 1);
auto hundreds = sum_of_ith_digit(v, 2);
std::for_each(std::cbegin(v), std::cend(v), [first=true](const int n) mutable {
std::cout << (first ? "v = " : ", ") << n; first = false; });
std::cout << "\n\tunits = " << units << ", tens = " << tens << ", hundreds = " << hundreds << "\n";
}
// Outputs:
// v = 123456, 99999, 100
// units = 15, tens = 14, hundreds = 14
下面的代码应该完全一样,尽管它可能更容易理解。 Demo
#include <iostream> // cout
#include <vector>
int sum_of_ith_digit(const std::vector<int>& v, size_t i)
{
// 1 for digit 0, 10 for digit 1, 100 for digit 2...
int divisor{1};
while (i != 0) { divisor *= 10; i--; }
// For each number in v, get ith digit, and add it to a total, then return the total
int total{0};
for (int n : v) { total += (n / divisor) % 10; }
return total;
};
int main()
{
std::vector<int> v{123'456, 99'999, 100};
int units = sum_of_ith_digit(v, 0);
int tens = sum_of_ith_digit(v, 1);
int hundreds = sum_of_ith_digit(v, 2);
std::cout << "v = ";
bool first{true};
for (int n : v)
{
if (not first) { std::cout << ", "; }
else { first = false; }
std::cout << n;
}
std::cout << "\n\tunits = " << units << ", tens = " << tens << ", hundreds = " << hundreds << "\n";
}
// Outputs:
// v = 123456, 99999, 100
// units = 15, tens = 14, hundreds = 14