Print1ToMaxNDigits

    xiaoxiao2024-11-06  2

    #include<stdio.h> #include<string.h> #include<windows.h> bool Increment(char* number){ bool overflow=false; int carryover=0; int length=strlen(number); for(int i=length-1;i>=0;i--){ int digit=number[i]-'0'+carryover; if(i==length-1) digit++; if(digit>=10){ if(i==0) overflow=true; else{ digit=digit-10; number[i]=digit+'0'; carryover=1; } } else{ number[i]=digit+'0'; break; } } return overflow; } void Print(char *number){ bool isBegin0=true; int length=strlen(number); for(int i=0;i<length;i++){ if(isBegin0&&number[i]!='0') isBegin0=false; if(!isBegin0){ //Sleep(50); printf("%2c",number[i]); } } printf("\n"); } void Print1ToMaxNDigits(int n){ if(n<=0){ printf("位数为小于等于0的数\n"); return; } char* number=new char[n+1]; memset(number,'0',n); number[n]='\0'; while(!Increment(number)){ Print(number); } delete[] number; } void Print1ToNDigits(char* number,int length,int index){ if(index==length-1){ Print(number); return ; } for(int i=0;i<10;i++){ number[index+1]=i+'0'; Print1ToNDigits(number,length,index+1); } } //递归 void Print1ToMaxNDigitsAgain(int n){ if(n<=0){ printf("位数为小于等于0的数\n"); return; } char* number=new char[n+1]; memset(number,'0',n); number[n]='\0'; for(int i=0;i<10;i++){ number[0]=i+'0'; Print1ToNDigits(number,n,0); } delete[] number; } void main(){ //Print1ToMaxNDigits(1); //Print1ToMaxNDigitsAgain(1); //Print1ToMaxNDigits(3); //Print1ToMaxNDigitsAgain(3); Print1ToMaxNDigits(0); Print1ToMaxNDigitsAgain(0); Print1ToMaxNDigits(-1); Print1ToMaxNDigitsAgain(-1); }
    转载请注明原文地址: https://ju.6miu.com/read-1293376.html
    最新回复(0)