大数问题
- 输入数字n,按顺序打印出从1到最大的n位十进制。
- 输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印出所有数字中最小的一个。
- 大数相加和大数相乘。
1、思路:
首先想到的方法必然是确定上限,比如n=3,上限是100。但是当n很大时,就算用long long也有可能溢出,所以考虑将数字转成字符处理。如果用字符来模拟加法操作,过程比较复杂。但是用数字全排列则能很好的解决问题,即各个位置上0~9都出现一遍。在打印的时候要注意,以0开头的字符不能打印出来。
Print1ToMax
1 #include <stdio.h> 2 #include <string.h> 3 4 void PrintNumber(char* number) 5 { 6 bool isBegin0 = true; 7 int nLength = strlen(number); 8 for (int i = 0; i < nLength; i++) 9 { 10 if (isBegin0 && number[i] != '0') 11 isBegin0 = false; 12 if (!isBegin0) 13 printf("%c", number[i]); 14 } 15 printf("\t"); 16 } 17 18 void PrintRecursively(char* number, int nLength, int index) 19 { 20 if (index == nLength - 1) 21 { 22 PrintNumber(number); 23 return; 24 } 25 for (int i = 0; i < 10; i++) 26 { 27 number[index] = i + '0'; 28 PrintRecursively(number, nLength, index + 1); 29 } 30 } 31 32 void Print1ToMax(int n) 33 { 34 if (n <= 0) 35 return; 36 char* number = new char[n + 1]; 37 number[n] = '\0'; 38 int index = 0; 39 PrintRecursively(number, n, index); 40 delete[] number; 41 } 42 43 int main() 44 { 45 int test = 3; 46 Print1ToMax(test); 47 }
2、思路:
只要按数字大小排序就行,但是考虑到数据溢出的问题,采用字符串排序的方式。首先先将整形,转字符串;再利用自带的qsort排序函数,排序字符串大小。
PrintMinNumber
1 #include <string> 2 #include <algorithm> 3 4 int compare(const void* strNumber1, const void* strNumber2); 5 6 const int g_MaxNumberLength = 10; 7 8 char* g_StrCombine1 = new char[g_MaxNumberLength * 2 + 1]; 9 char* g_StrCombine2 = new char[g_MaxNumberLength * 2 + 1]; 10 11 void PrintMinNumber(int* numbers, int length) 12 { 13 if (numbers == NULL || length <= 0) 14 return; 15 16 //char** strNumbers = (char**)(new int[length]); 17 char** strNumbers = new char*[length]; 18 for (int i = 0; i < length; ++i) 19 { 20 strNumbers[i] = new char[g_MaxNumberLength + 1]; 21 sprintf(strNumbers[i], "%d", numbers[i]); 22 } 23 24 //compare传入的是数组元素的地址 25 qsort(strNumbers, length, sizeof(char*), compare); 26 27 for (int i = 0; i < length; ++i) 28 printf("%s", strNumbers[i]); 29 printf("\n"); 30 31 for (int i = 0; i < length; ++i) 32 delete[] strNumbers[i]; 33 delete[] strNumbers; 34 } 35 36 int compare(const void* strNumber1, const void* strNumber2) 37 { 38 //因为strNumber是指向字符串的地址,所以需要经过转化 39 strcpy(g_StrCombine1, *(const char**)strNumber1); 40 strcat(g_StrCombine1, *(const char**)strNumber2); 41 42 strcpy(g_StrCombine2, *(const char**)strNumber2); 43 strcat(g_StrCombine2, *(const char**)strNumber1); 44 45 return strcmp(g_StrCombine1, g_StrCombine2); 46 } 47 48 int main() 49 { 50 int numbers[] = {3, 46, 5, 17, 2}; 51 PrintMinNumber(numbers, 5); 52 }