首页 > 代码库 > 剑指Offer10 打印1到最大n位数

剑指Offer10 打印1到最大n位数

  1 /*************************************************************************  2     > File Name: 10_PrintToMaxNum.c  3     > Author: Juntaran  4     > Mail: JuntaranMail@gmail.com  5     > Created Time: 2016年08月30日 星期二 00时47分36秒  6  ************************************************************************/  7   8 #include <stdio.h>  9 #include <malloc.h> 10 #include <string.h> 11  12  13 void PrintNumber(char* number) 14 { 15     bool isBeginning0 = true; 16     int length = strlen(number); 17      18     for (int i = 0; i < length; ++i) 19     { 20         if (isBeginning0 && number[i]!=0) 21             isBeginning0 = false; 22          23         if (!isBeginning0) 24             printf("%c", number[i]); 25     } 26     printf("\t"); 27 } 28  29  30 bool Increment(char* number) 31 { 32     bool isOverflow = false; 33     int length = strlen(number); 34     int TakeOver = 0; 35      36     for (int i = length-1; i >= 0; i--) 37     { 38         int sum = number[i] - 0 + TakeOver;    // 进位 39         if (i == length - 1) 40             sum ++; 41          42         if (sum >= 10) 43         { 44             if (i == 0) 45                 isOverflow = true; 46             else 47             { 48                 sum -= 10; 49                 TakeOver = 1; 50                 number[i] = sum + 0; 51             } 52         } 53         else 54         { 55             number[i] = sum + 0; 56             break; 57         } 58     } 59     return isOverflow; 60 } 61  62 // 从1打印到最大的n位数 63 void PrintToMaxNum1(int n) 64 { 65     if (n <= 0) 66         return; 67      68     char* number = (char*)malloc(sizeof(char)*(n+1)); 69     memset(number, 0, n); 70     number[n] = \0; 71      72     while (!Increment(number)) 73     { 74         PrintNumber(number); 75     } 76     free(number); 77 } 78  79  80 /************************************************************************/ 81 // 递归写法 82 void PrintToMaxNumRecursively(char* number, int length, int index) 83 { 84     if (index == length-1) 85     { 86         PrintNumber(number); 87         return; 88     } 89     for (int i = 0; i < 10; ++i) 90     { 91         number[index+1] = i + 0; 92         PrintToMaxNumRecursively(number, length, index+1); 93     } 94 } 95  96 void PrintToMaxNum2(int n) 97 { 98     if (n <= 0) 99         return;100     101     char* number = (char*)malloc(sizeof(char)*(n+1));102     number[n] = \0;103     104     for (int i = 0; i < 10; ++i)105     {106         number[0] = i + 0;107         PrintToMaxNumRecursively(number, n, 0);108     }109     free(number);110 }111 112 113 int main()114 {115     int n = 5;116     PrintToMaxNum1(n);117     PrintToMaxNum2(n);118 }

 

剑指Offer10 打印1到最大n位数