【问题标题】:How can I check if a number have the same digits? (in a func) [closed]如何检查一个数字是否具有相同的数字? (在函数中)[关闭]
【发布时间】:2014-08-20 15:33:56
【问题描述】:

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

例如:

110、292等相同,无效。

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

【问题讨论】:

  • 显示一些代码。我们无法修复我们看不到的东西。否则,不清楚您需要什么帮助。
  • 除了发布一些代码之外,对您使用的推理进行更多解释会有所帮助。

标签: c++ function


【解决方案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;
}

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

【讨论】:

  • 对不起,我的意思是一个大小为 10 的字符数组。你在“缓存[基础]”中检查什么?
  • 我避免使用vector,所以我使用vector。除了不是 0 字符外,与“T”无关。该解决方案适用于任何基数,因此您可以查找十六进制或任何其他基数的重复数字。当然,在基数 2 中,每个数字都有重复的数字,除了 0、1 和 10 (2)
【解决方案2】:

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

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++;
}

【讨论】:

  • 另外,我只是注意到你告诉的是一个 10 字符数组,所以如果数组不是以 null 结尾的,你只需要用 for(int n = 0; n
  • 这是标记为 C++,所以也许更 C++ 的方法是合理的?
  • 好吧,我发现字符串迭代器和 std::set 不太适合用户请求......而且我个人认为它的效率较低。
  • 例如,您可以使用 bool 数组并将其初始化为零 (bool found[10] = {};)
【解决方案3】:

可能的实施:

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-10
    • 1970-01-01
    • 1970-01-01
    • 2014-01-31
    • 2021-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多