Как сложить цифры разрядов числа?
Например, есть число - 1204. Надо, чтобы оно сложило цифры каждого разряда (1 + 2 + 0 + 4). Как это сделать?
Ответы (4 шт):
Автор решения: dIm0n
→ Ссылка
Вот так вот:
#include <string>
#include <iostream>
#include <numeric>
int main() {
constexpr auto x = 1204;
const auto s = std::to_string(x);
std::cout << std::accumulate(std::cbegin(s), std::cend(s), 0, [](auto acc, auto x) {
return acc + (x - '0');
}) << '\n';
}
Автор решения: olkhovich
→ Ссылка
int solution(int number) {
int sum = 0;
while (number) {
sum += number % 10;
number /= 10;
}
return sum;
}
Автор решения: AR Hovsepyan
→ Ссылка
Я бы учел, что число может быть отрицательным. Ну и еще один вариант:
unsigned g(int n)
{
n = std::abs(n);
if (n < 10)
return n;
std::stringstream io;
io << n;
n = 0;
char t;
while (io >> t)
n += t - '0';
return n;
}
Автор решения: Harry
→ Ссылка
Раз тут начались споры, что быстрее... Эксперимент
unsigned int Hovsepyan()
{
unsigned int sum = 0;
for(int n = 0; n < Count; ++n)
{
n = std::abs(n);
if (n < 10) { sum += n; continue; }
std::stringstream io;
io << n;
char t;
while (io >> t)
sum += t - '0';
}
return sum;
}
unsigned int olkhovich()
{
unsigned int sum = 0;
for(int n = 0; n < Count; ++n)
{
int number = n;
while (number) {
sum += number % 10;
number /= 10;
}
}
return sum;
}
unsigned int dIm0n()
{
unsigned int sum = 0;
for(int n = 0; n < Count; ++n)
{
const auto s = to_string(n);
sum += accumulate(cbegin(s), cend(s), 0,
[](auto acc, auto x) {
return acc + (x - '0');});
}
return sum;
}
int main(int argc, const char * argv[])
{
{
muTimer mt;
unsigned int s = Hovsepyan();
mt.stop();
cout << "Hovsepyan() == " << s << " for " << mt.duration<>() << " mks\n";
}
{
muTimer mt;
unsigned int s = olkhovich();
mt.stop();
cout << "olkhovich() == " << s << " for " << mt.duration<>() << " mks\n";
}
{
muTimer mt;
unsigned int s = dIm0n();
mt.stop();
cout << "dIm0n() == " << s << " for " << mt.duration<>() << " mks\n";
}
}
(полный код здесь) дает на моей машине (VC++ 2019) и на Ideone (GCC) следующие результаты в мкс:
VС++ 2019 GCC
olkhovich() 8324 6970
dIm0n() 19634 80521
Hovsepyan() 1310028 434293
Так что моя рекомендация - принять ответ olkhovich - остается в силе :)