检查数字重复数字的最快方法是什么?

Cha*_*han 5 algorithm numbers

假设我想检查数字n = 123是否有重复的数字.我试过了:

#include <iostream>

using namespace std;

int main() {
    int n = 123;
    int d1 = n % 10;
    int d2 = ( n / 10 ) % 10;
    int d3 = ( n / 100 ) % 10;
    if( d1 != d2 && d1 != d3 && d2 != d3 ) {
        cout << n << " does not have duplicate digits.\n";
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有更快的解决方案来解决这个问题?

更新
很抱歉不清楚.上面的代码是用C++编写的,仅用于描述目的.我必须在TI-89中解决这个问题,其中包含9位数字.由于内存和速度的限制,我正在寻找一种最快的方式.

TI-89只有几个条件关键字:

  • 如果
  • 如果......然后
  • 什么时候(
  • 对于...... EndFor
  • 虽然...... EndWhile
  • 循环...... EndLoop
  • 自定义... EndCustom

谢谢,

pax*_*blo 10

更快,可能不是(但你应该测量,以防万一 - 我的优化口号是"measure, don't guess").但我认为,更明确的意图,并且能够处理任意大小的整数.

int hasDupes (unsigned int n) {
    // Flag to indicate digit has been used.

    int i, used[10];

    // Must have dupes if more than ten digits.

    if (n > 9999999999)
        return 1;

    // Initialise dupe flags to false.

    for (i = 0; i < 10; i++)
        used[i] = 0;

    // Process all digits in number.

    while (n != 0) {
        // Already used? Return true.

        if (used[n%10])  // you can cache n%10 if compiler not too smart.
            return 1;

        // Otherwise, mark used, go to next digit.

        used[n%10] = 1;  // and you would use cached value here.
        n /= 10;
    }

    // No dupes, return false.

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果您的可能性有限,您可以使用历史悠久的方法来牺牲空间.

假设你在谈论0到999之间的数字:

const int *hasDupes = {
//  0  1  2  3  4  5  6  7  8  9
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  //   x
    0, 1, 0, 0, 0, 0, 0, 0, 0, 0,  //  1x
    0, 0, 1, 0, 0, 0, 0, 0, 0, 0,  //  2x
    :
    0, 0, 0, 0, 0, 0, 0, 1, 0, 1,  // 97x
    0, 0, 0, 0, 0, 0, 0, 0, 1, 1,  // 98x
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 99x
};
Run Code Online (Sandbox Code Playgroud)

并只是做一个表查找hasDupes[n].


根据你需要处理九位数的编辑,你的计算器可能无法实现十亿元素阵列(上面的第二个解决方案):-)

我会选择第一个解决方案.