计算整数的十进制表示中的不同数字的数量

时间:2012-10-01 19:32:02

标签: c++

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

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

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

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

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

有人可以说明我是如何做到的吗?

5 个答案:

答案 0 :(得分: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();
}

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

答案 1 :(得分: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;
}

这仅适用于正数和负数。

答案 2 :(得分: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;
}

答案 3 :(得分:1)

你可以很好地计算不同的数字,但是无法从'a'the value of the variable a;。你可以硬编码 - 但这相当重要。

答案 4 :(得分:-1)

如果你想返回一个浮点来获得一个十进制,只需将它作为一个浮点数返回,编译器应该进行隐式类型转换。这通常不是好的代码,但它的工作原理。更好的方法可能是将值交给像

这样的临时浮点数
float a_float = a;
return a_float;
相关问题