C ++ print all numbers whose digits are n

Source: Internet
Author: User

C ++ print all numbers whose digits are n

Method 1: array and Recursion # include
  
   
Using namespace std; void General (int B [], int n, int k) {if (n <= 0) // k indicates the number of digits to print, and n indicates the number of digits to be recursive. {If (k! = 1) {while (B [k-1] = 0) // remove the top 0 {k --;} if (k = 1) return ;} for (int j = K-1; j> = 0; j --) {cout <B [j] <"; if (j = 0) cout <endl;} return;} for (int I = 0; I <10; I ++) // I feel that I am not very handy. {B [n-1] = I; General (B, n-1, k); // recursive value assignment of one digit, the value range is 0-9 }}void Grial (int n) {if (n <= 0) return; int * B = new int [n]; // B [n] cannot be used in vs2013, because it considers n as an uninitialized value. Memset (B, 0, n); for (int I = 1; I <= n; I ++) {int k = I; General (B, I, k) ;}} int main () {Grial (3); return 0 ;}
  

Method 2: String implementation:

# Include
  
   
Using namespace std; void ADD (char * str, int n, int & x) {int flags = 1; char * p = str + n-1; while (flags! = 0) {flags = 0; if (* (p) + flags-'0') = 9) {flags = 1; * (p) = '0';} else {* (p) = * (p)-'0' + '1';} p --; if (* str = '9' & flags = 1 & * p = '9') // if the maximum bit is 9, and the next high is 9, flags = 1 {// then the judgment is over, set the flag bit to 1, and return termination. X = 1; return ;}} void Printf (char * str) // print, remove the first 0 {char * p = str; while (* p = '0') {p ++;} cout <p <endl;} void Grial (int n) {if (n <= 0) return; char * str = new char [n]; memset (str, '0', n); * (str + n) = '\ 0'; int flags = 0; // serves as the end mark. While (1) {Printf (str); ADD (str, n, flags); // ADD 1. if (flags = 1) break;} int main () {Grial (2); return 0 ;}
  

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.