# Print n digits from 1 to the maximum

Source: Internet
Author: User

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 ;}`
Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.