Print n digits from 1 to the maximum

Source: Internet
Author: User

The main consideration is the big number problem. N can easily exceed the range expressed by positive numbers, so it needs to be simulated using character arrays.

Add 1 first and then print. As follows:


# Include <stdio. h> # include <stdlib. h> // 1 is returned for overflow. Otherwise, 0int add (char * number) {int overflow = 0, I, current_value; int nLength = strlen (number), jinwei = 0; for (I = nLength-1; I> = 0; I --) {current_value = number [I]-'0' + jinwei; // Add carry if (I = nLength-1) for each bit // Add 1 current_value ++ for the second bit; if (current_value> = 10) {// when the value is equal to 10, carry if (I = 0) overflow = 1; // when the highest bit needs to be carried, it indicates that the maximum value of else {current_value-= 10 has been reached ;/ /If it is not the highest bit, the carry operation is required. First, the current BIT is subtracted from 10, and then the carry flag is set to use jinwei = 1 next time; number [I] = '0' + current_value ;}} else {// assign current_value to the number bit without carrying it. Then, the number [I] = '0' + current_value; break ;}} return overflow ;} // print this number and ignore the 0 void print_a_number (char * number) {int begin = 0, I; for (I = 0; I <strlen (number ); ++ I) {if (! Begin & number [I]! = '0') begin = 1; if (begin) printf ("% c", number [I]);} printf ("\ t ");} void print_all (int n) {char * number = (char *) malloc (n + 1) * sizeof (char); if (n <= 0) return; memset (number, '0', n); number [n] = '\ 0'; while (! Add (number) {print_a_number (number);} free (number) ;}void main () {print_all (2); getch ();}


Reference offoffoffer

Contact Us

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.