比方说,我要检查,如果一个数n = 123有重复的数字。我想:
Let's say I want to check if a number n = 123 has duplicate digits. I tried:
#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";
}
}
有没有更快的办法解决这个问题?
Is there any faster solution to this problem?
更新 对不起,我是不清楚。在code以上是用C ++编写仅用于说明目的。我要解决TI-89这样的问题,与一些9位。而且,由于内存和速度的限制,我在寻找一个可以最快的方式。
Update Sorry for being unclear. The code above was written in C++ only for description purpose. I have to solve this problem in TI-89, with a number of 9 digits. And since the limitation of memory and speed, I'm looking for a fastest way possible.
TI-89只有几个条件关键字:
TI-89 only has several condition keyword:
如果 如果...那么 时( 有关... ENDFOR 虽然... ENDWHILE 在环... ENDLOOP 在自定义... EndCustom谢谢, 成龙
更快,可能不是(但你应该无论如何衡量,以防万一 - 我的优化口头禅是的措施,不用猜
)。但在意图更加清晰,我想,是的,并且能够处理任意大小的整数。
Faster, possibly not (but you should measure anyway, just in case - my optimisation mantra is "measure, don't guess"
). But clearer in intent, I think, yes, and able to handle arbitrary sized integers.
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;
}
如果您有机会在有限的范围内,可以用牺牲空间换取时间的由来已久的做法。
If you have a limited range of possibilities, you can use the time-honoured approach of sacrificing space for time.
假设你正在谈论数的0和999之间:
Say you're talking of numbers between 0 and 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
};
和刚做 hasDupes的查表[N]
。
时,可能不会有可能在你的计算器: - )
Based on your edit when you need to handle nine digits, a billion-element array (second solution above) is probably not going to be possible on your calculator :-)
我会选择第一个解决方案。
I would opt for the first solution.