找到最小的数字

时间:2015-09-22 12:11:40

标签: c algorithm

我的C编程问题是找到最小的好的n位数字。序列是1213,然后用户输入一个数字,1213出现的次数将取决于输入。例如:

(input: 1   output:1)      (input:2    output:12)  (input:3    output:121)   (input:4  output: 1213)  (input:5 output:12131)  (input:6   output:121312)    (input:7    output: 1213121)    

序列将被重复,输入的数字将告诉输出序列将出现多少位数,但应遵循序列,1213

现在我所创造的是:

include<stdio.h>  
#include<stdlib.h>  
main() 
{   
    int a, x, num, ar[500]  
    printf("Input an integer: ");
    scanf("%d",&a);  
    printf("The smallest good number of %d number": );  
    scanf("%d", &num);  ar[x]=num; 
}        

那只是要求用户输入一个号码,然后我不知道如何制作1213号。

1 个答案:

答案 0 :(得分:1)

#include<stdio.h>  
#include<stdlib.h>
int main()
{ unsigned int a, num, i, len; char result[500], aStr[9];
  printf("\nInput a positive integer less than 8 digits: "); scanf("%u", &a);  
  printf("\nInput a number of digits between 1 and 500: "); scanf("%u", &num);

  // convert the input number a to string aStr and calculate its length
  snprintf(aStr, 9, "%u", a); len = strlen(aStr);
  // print the digits in result until the desired length is reached
  for(i=0; i < num; i++) result[i] = aStr[i % len];
  *i = 0; // terminate the string
  printf("The smallest good number is: %s\n", aStr);

  return 0;
}