1 条题解

  • 0
    @ 2082-11-30 20:44:26

    【例32.3】 数位积

    解题思路

    每组令乘积为 1,循环取末位 n%10 相乘并除 10。使用 do-while,让 n=0 也处理一位零,得到乘积 0。

    正确性说明

    按上述推导执行:每次仅处理当前输入或当前步骤,并把它对答案的贡献计入对应状态。所有需要处理的情况均被覆盖,结束时保存的量就是题目所求。

    易错点

    含任何一位 0 则乘积为 0;零输入不能跳过循环。

    复杂度

    T 组、每组 D 位,时间 O(TD),空间 O(1)。

    参考代码(C++11)

    #include <bits/stdc++.h>
    using namespace std;
    
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        int T;
        cin >> T;
        while (T--) {
            long long n;
            cin >> n;
            long long product = 1;
            do {
                product *= n % 10;
                n /= 10;
            } while (n);
            cout << product << "\n";
        }
        return 0;
    }
    
    • 1