You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求各位数字乘积等于给定数的最小数:代码未过测试求助

排查「各位数字乘积等于给定数的最小数」代码问题

我是编程新手,现在要解决的问题是找到各位数字乘积等于给定数的最小数,如果没法构造就输出-1。问题示例如下:

10 = 25(25=10)
13 = -1
5 = 5
100 = 455(4
5*5=100)

输入是单个数字n,范围是0 ≤ n ≤ 10^9。我基于教程写的代码本地运行正常,但竞赛网站提交后没法通过全部测试用例,而且测试用例是隐藏的,不知道哪里错了,希望能找出失败的测试用例或者排查代码问题。

我的代码如下:

#include <iostream>
#include <stack>
using namespace std;

// function to find smallest number k such that
// the product of digits of k is equal to n
long long int smallestNumber(long long int n) {
    // if 'n' is a single digit number, then
    // it is the required number
    if (n >= 0 && n <= 9)
        return n;

    // stack the store the the digits
    stack<long long int> digits;

    // repeatedly divide 'n' by the numbers
    // from 9 to 2 until all the numbers are
    // used or 'n' > 1
    for (long long int i = 9; i >= 2 && n > 1; i--) {
        while (n % i == 0) {
            // save the digit 'i' that divides 'n'
            // onto the stack
            digits.push(i);
            n = n / i;
        }
    }

    // if true, then no number 'k' can be formed
    if (n != 1)
        return -1;

    // pop digits from the stack 'digits'
    // and add them to 'k'
    long long int k = 0;
    while (!digits.empty()) {
        k = k * 10 + digits.top();
        digits.pop();
    }

    // required smallest number
    return k;
}

// Driver program to test above
int main() {
    long long int n;//number i want to convert
    cin >> n;
    cout << smallestNumber(n);
    return 0;
}

可能的问题与失败测试用例分析

你的代码逻辑整体是正确的:从9到2分解因数,用栈存储保证最终数字的高位尽可能小,边界处理也覆盖了大部分情况,但有一个非常容易忽略的隐含边界场景可能导致测试用例失败:

1. n=0的处理不符合题目隐含要求

你的代码中,n=0会直接返回0,但如果竞赛题目中的「数」被定义为正整数(即排除0本身),那么乘积为0的最小正整数应该是10,而不是0。这是很多竞赛题的常见隐含规则——题目默认找的是正整数,而非包含0的自然数。

如果测试用例中包含n=0,且题目期望返回10而非0,你的代码就会失败。

2. 验证其他边界场景

  • n=1:你的代码返回1,这是正确的(1是乘积为1的最小数,没有比它更小的正整数)。
  • 大数值场景:比如n=1e9,分解后的数字是555555555888,long long int完全可以容纳,不会出现溢出问题。
  • 无法构造的场景:比如n=13,代码返回-1,符合示例要求。

修复建议

如果是n=0的场景导致失败,可以修改代码开头的边界判断:

if (n == 0)
    return 10; // 若题目要求返回最小正整数
else if (n >= 1 && n <= 9)
    return n;

如果题目明确允许0作为答案(比如定义「数」包含0),那你的代码这部分是正确的,可能需要进一步排查是否有其他极端测试用例(比如n=1是否被题目特殊处理,但根据示例逻辑,n=1返回1是合理的)。

内容的提问来源于stack exchange,提问作者katinas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:19:57