3

我是 C++ 开发的新手,我希望有人可以帮助我完成我一直在尝试做的事情。

比如说我想要一个函数,给定一个整数输入,返回它包含的不同数字的数量。

例如,如果我有三个整数:

int a = 19876;
int b = 25644;
int c = 4444;

如果我将“a”传递给函数,我希望返回数字 5。如果将“b”传递给函数,我希望返回“4”,如果将“c”传递给函数,则将返回 1,因为它们是不同数字的数量。

有人可以说明我如何实现这一目标吗?

4

5 回答 5

6

你的意思是你想找到整数中不同十进制数字的数量?

int distinct_digits(int value) {
    std::ostringstream out;
    out << value;
    std::string digits = out.str();
    std::sort(digits.begin(), digits.end());
    return std::unique(digits.begin(), digits.end()) - digits.begin();
}

(未编译或测试,但基本思想应该有效)

于 2012-10-01T19:38:28.047 回答
5

使用 mod 运算符,您可以计算它:

int distinct(int a)
{
    int ele[10]={0};

    if(a==0) return 1;
    if(a<0) a=a*-1;

    while(a)
    {
        int t=a%10;
        ele[t]=1;
        a=a/10;
    }

    for (i=0;i<10;i++)
        if (ele[i])
            count++;

    return count;
}

这仅适用于正数和负数。

于 2012-10-01T19:38:32.150 回答
4

这可能更简洁,但我正在帮助您了解解决方案的工作方式。

int digitCount(int number) {
    // make an array to store whether you've seen a given digit
    // note that there are 10 elements, one for each digit
    // this will be conveniently indexed 0-9
    bool digitSeen[10];

    // set each seen digit
    int count = 0;
    while (number != 0) {
        // get the rightmost digit with the modulo operator (%)
        int digit = number % 10;
        if (digitSeen[digit] == false) {
            // only count if this is the first time we have seen it
            ++count;
            digitSeen[digit] = true;
        }
        // pop off the right-most digit by dividing by 10
        number /= 10;
    }

    return count;
}
于 2012-10-01T19:41:27.560 回答
1

您可以很好地计算不同的数字,但是没有办法从'a'the value of the variable a;。您可以对其进行硬编码 - 但这是相当繁重的维护工作。

于 2012-10-01T19:35:05.533 回答
-1

如果您的意思是返回一个浮点以获得小数,只需将其作为浮点数返回,编译器应该进行隐式类型转换。这通常不是好的代码,但它可以工作。更好的方法可能是将值交给临时浮动,例如

float a_float = a;
return a_float;
于 2012-10-01T19:35:45.273 回答