Question: Enter the value n and print the N digits from 1 to the maximum in sequence. For example, if n is 3, the number is printed from 1, 2, 3 to 999.
Trap: If loop traversal is used, 1-999... 9 and output in sequence. When the number N is too large, it will overflow no matter whether it is saved into int, long, or long. Therefore, the string is used to simulate the Number Addition.
# Include <stdio. h> # include <stdlib. h> # include <string. h> void print_cur_number (char * s) {char * P = s; while (* P! = '\ 0') {If (* P = '0') // locate the first non-0 digit position P ++; else break ;} printf ("% s \ n", P);} int increase_one (char * s) {int I; int Len = strlen (s); int carry = 0; // carry sign int over = 0; // over = 1, indicating that the current value is already the maximum value of N digits, plus + 1 will become N + 1 digits for (I = len-1; I> = 0; I --) {int sum = s [I]-'0' + carry; if (I = len-1) + + sum; // first loop, second bit + 1 If (sum> = 10) // Current BIT> = 10, you need to enter one {if (I = 0) in the first one // The carry where the highest bit occurs, indicating that the current value (before the plus 1) is already the maximum n digits over = 1; Else // carry of non-highest bits {sum-= 10; s [I] = '0' + sum; carry = 1 ;}} after else // current value + 1, no carry occurred. The end loop {s [I] = sum + '0'; break ;}} return over;} void print_to_max_n_digit (INT N) {char * s = malloc (n + 1); memset (S, '0', n); s [N] = '\ 0'; If (n <= 0) return; while (! Increase_one (s) {print_cur_number (s);} Free (s);} int main (void) {int N; printf ("Print 1-maximum N-digits, enter N: "); scanf (" % d ", & N); print_to_max_n_digit (n); Return 0 ;}