求和 3 个数字的最快方法

Fastest way to sum 3 numbers digits

我的老师要求我解决这个问题:"You get 3 different numbers as input, of different length, you have to determine the sum of the digits of all 3 numbers and also the product" 我是这样解决的:

#include <bits/stdc++.h>

using namespace std;

int main () {
    int a, b, c, S, P;
    cin >> a >> b >> c;
    S = 0;
    P = 1;

    while (a != 0) {
        int c1 = a % 10;
        S += c1;
        P *= c1;
        a /= 10;
    }
    while (b != 0) {
        int c1 = b % 10;
        S += c1;
        P *= c1;
        b /= 10;
    }
    while (c != 0) {
        int c1 = c % 10;
        S += c1;
        P *= c1;
        c /= 10;
    }
    cout << S << ' ' << P << endl;
}

我的问题是,有没有办法更有效地解决这个问题?

将重复的代码移到单独的函数中。

#include <iostream>
using namespace std;

void calc(int num, int &sum, int &product) {
    do {
        int c1 = num % 10;
        sum += c1;
        product *= c1;
        num /= 10;
    }
    while (num != 0);
} 

int main () {
    int a, b, c, S = 0, P = 1;
    if (cin >> a >> b >> c) {
        calc(a, S, P);
        calc(b, S, P);
        calc(c, S, P);
        cout << S << ' ' << P << endl;
    }
    return 0;
}

您不应该为这样一个简单的程序没有意义的最快方法而烦恼,而应该为代码的正确性和避免重复而烦恼。

你的程序不正确。

对于初学者,用户可以中断输入。在这种情况下,至少变量 a、b、c 之一将具有不确定的值。因此,该程序将具有未定义的行为。

其次,当用户可以输入负数时,您使用的是signed int类型。在这种情况下,您将得到不正确的结果,因为例如数字总和可能为负数。

第三,用户可以输入 0 作为数字的值。在这种情况下,这个数字将在像这样的 while 循环中被跳过

while (a != 0) {

在这种情况下,您将再次得到不正确的结果,因为数字的乘积可以不等于零,尽管在这种情况下它必须等于零。

重复了相同的 while 循环。那就是程序有冗余代码。

程序可以这样写,如下面的演示程序所示。

#include <iostream>

int main() 
{
    long long int a = 0, b = 0, c = 0;

    std::cin >> a >>b >> c;

    long long int sum = 0;
    long long int product = 1;

    for ( int num : { a, b, c } )
    {
        const long long int Base = 10;
        do
        {
            long long int digit = num % Base;

            if ( digit < 0 ) digit = -digit;

            sum += digit;
            if ( product ) product *= digit;
        } while ( num /= Base );
    }

    std::cout << "sum = " << sum << '\n';
    std::cout << "product = " << product << '\n';

    return 0;
}