Created
May 27, 2015 05:08
-
-
Save knowlet/6d4cc4a11e77cd33bf18 to your computer and use it in GitHub Desktop.
Write a C program which reads an integer number n and produces all n-digit numbers with no repeated digits.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
int increase(char* a, int n); | |
int checkRepeat(char* a, int n) | |
{ | |
int i, j; | |
for (i = 0; i < n-1; ++i) | |
// 檢查數字中是否有重複出現的數字 | |
for (j = i + 1; j < n; ++j) | |
// 檢查數字中是否有重複出現的數字 | |
if (a[i] == a[j]) | |
// 數字相同則呼叫加法函數加一 | |
return increase(a, n); | |
return 1; | |
} | |
int increase(char* a, int n) | |
{ | |
int m = n; | |
// 保留數量 | |
a[n-1] = a[n-1] + 1; | |
// 將個位數加一 | |
while (n--) { | |
// 跑回圈檢查進位 | |
if (a[n] - '0' == 10) { | |
// 如果進位則 | |
if (!n) return 0; | |
// 如果 carry 則回傳0結束迴圈 | |
a[n] = '0'; | |
// 進位則將目前位數設成0 | |
a[n-1] = a[n-1] + 1; | |
// 進位則下一個位數加一 | |
} | |
} | |
// 遞迴檢查重複的數字(不過實測了一下數字太大遞迴會爆炸,我的電腦大概可以跑到6位數) | |
return checkRepeat(a, m);; | |
} | |
void init(char* a, int n) | |
{ | |
int i; | |
a[0] = '1'; // 第一個數字設為一 | |
for (i = 1; i < n; ++i) | |
a[i] = '0'; // 其餘為零 | |
if (checkRepeat(a, n)) | |
// 檢查初始化的數字是否重複 | |
puts(a); | |
// 輸出 | |
} | |
int main(int argc, char const *argv[]) | |
{ | |
char* array; // 使用字元陣列方便輸出也節省記憶體 | |
int n; // 記錄使用者的輸入,也就是幾個數字 | |
while (scanf("%d", &n) && n > 0) { | |
// 判斷是否檔案結尾以及輸入的數字必須大於0 | |
array = (char*)calloc(n + 1, sizeof(char)); | |
// 動態宣告記憶體,也就是說使用者輸入3則宣告為4的陣列,並且初始化為0 | |
init(array, n); | |
// 初始化,將陣列初始化成開頭為一其餘為零 | |
while (increase(array, n)) | |
// 數字加一 | |
puts(array); | |
// 輸出結果 | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment