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?
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 only has several condition keyword:
- If
- If … Then
- when(
- For … EndFor
- While … EndWhile
- Loop … EndLoop
- Custom … EndCustom
Thanks,
Chan
Not necessarily faster but you should measure anyway, just in case – my optimisation mantra is
"measure, don't guess".But I believe it’s clearer in intent (and simple enough to be translated to a simpler calculator language. It’s also able to handle arbitrarily sized integers.
If you have a limited range of possibilities, you can use the time-honoured approach of sacrificing space for time. For example, let’s say you’re talking about numbers between 0 and 999 inclusive (the
: :markers simply indicate data I’ve removed to keep the size of the answer manageable):and just do a table lookup of
hasDupes[n]. The table itself could be generated (once) programmatically and then just inserted into your code for usage.However, based on your edit where you state you need to handle nine-digit numbers, a billion-element array is probably not going to be possible on your calculator. I would therefore opt for the first solution.