如何检查数字是否具有相同的数字? (在一个功能中)

时间:2014-08-20 15:33:56

标签: c++ function

我想在c ++中构建一个在[10] char数组上运行的函数,所以我想检查一下我在数组的当前位置是否有相同的数字。

例如:

110,292等具有相同且无效。

123,345678,98732,3,125有效。

3 个答案:

答案 0 :(得分:1)

可以通过多种方式完成,但快速提供的是设置数组以检查是否已找到数字,例如:

char found[10];
memset(found,0x00,10);

char* c = yourbuffer;
while (c) {
    int digit = c - '0';
    if (!found[digit]) found[digit] = 1;
    else /* NOT UNIQUE, BREAK AND SET ERROR ACCORDING */
    c++;
}

答案 1 :(得分:1)

不确定[10] char array

的含义

如果您想查看某个数字在基数10中是否有任何数字显示两次,您可以使用std::bitset或类似数字,然后使用x % 10获取数字x /= 10直到x变为0

bool hasRepeatedDigit( unsigned int num, unsigned int base )
{
    std::vector< char > cache( base ); // avoiding vector<bool>

    while( num )
    {
       unsigned int digit = num % base;
       if( cache[ base ] )
          return true;

       cache[ base ] = 'T'; // just mark it
       num /= base;
    }

    return false;
}

这是通用的,假设您有一个数字作为数字,而不是字符串。如果它只是一个字符串,它将以不同的方式实现。

答案 2 :(得分:0)

可能的实施:

bool hasDupDigits(char const *array, std::size_t size) {
    // If there are more than ten digits, there ought to be duplicates.
    if(size > 10)
        return true;

    // Using ten bits to store whether we already encountered a digit
    unsigned short storage = 0, mask;

    // Will stop on a null-terminator or after size chars.
    for(; size && *array; ++array, --size) {
        // Find which bit we are to consider
        mask = ((short)1) << (*array) - '0';
        // Return if we already set that bit
        if(storage & mask)
            return true;
        // Set the bit
        storage |= mask;
    }

    // No duplicate encountered
    return false;
}