作者Frozenmouse (*冰之鼠*)
看板Programming
标题Re: [问题] 1-9位数不重复印出来 (C++ template)
时间Wed Dec 14 11:43:40 2016
※ 引述《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
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 1.171.99.34
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Programming/M.1481687024.A.5BE.html
※ 编辑: Frozenmouse (1.171.99.34), 12/14/2016 11:47:58
1F:→ Neisseria: 刚试了一下,INPUT = 6 时,程式编不完 125.227.36.84 12/14 16:44
2F:→ Neisseria: 不知道是不是记忆体不足,後来 kill 掉 125.227.36.84 12/14 16:44
3F:→ Neisseria: 就放弃了。总之,还是蛮有趣的 XD 125.227.36.84 12/14 16:46
4F:推 CindyLinz: "求救援" => 募资买记忆体! :D 112.121.78.5 12/15 00:31