Re: [問題] 1-9位數不重複印出來 (C++ template)

作者: Frozenmouse (*冰之鼠*)   2016-12-14 11:43:40
※ 引述《mikemagic88 (Mikemagic88)》之銘言:
: 使用者輸入1 印1-9
: 使用者輸入2 印1-98 (11, 22, 33等重複的不印)
: 使用者輸入3 印1-987 (121, 988, 667等有重複的不印)
#include <iostream>
using namespace std;
#ifndef INPUT
#define INPUT 3
#endif
template<int Length, int Flags = 0, int LastDigit = 9, int Number = 0>
struct SolutionFinder {
static void exec() {
SolutionFinder<Length, Flags, LastDigit - 1, Number>::exec();
if (!Number || !(Flags & (1 << LastDigit))) {
SolutionFinder<
Length - 1,
Flags | (1 << LastDigit),
9,
Number * 10 + LastDigit
>::exec();
}
}
};
template<int Length, int Flags, int Number>
struct SolutionFinder<Length, Flags, -1, Number> {
static void exec() { }
};
template<int Flags, int LastDigit, int Number>
struct SolutionFinder<0, Flags, LastDigit, Number> {
static void exec() {
if (Number) cout << Number << endl;
}
};
int main() {
SolutionFinder<INPUT>::exec();
return 0;
}
使用範例:
$ g++ -O3 -DINPUT=3 -o test3 test.cpp
$ ./test3
中規中矩(?)的版本
不過編到 INPUT >= 6 記憶體就不夠用了,求救援 XD

Links booklink

Contact Us: admin [ a t ] ucptt.com