关于PTA 7-49 Have Fun with Numbers中的代码实现

7-49 Have Fun with Numbers(20 分)

Notice that the number 123456789 is a 9-digit number consisting exactly the numbers from 1 to 9, with no duplication. Double it we will obtain 246913578, which happens to be another 9-digit number consisting exactly the numbers from 1 to 9, only in a different permutation. Check to see the result if we double it again!

Now you are suppose to check if there are more numbers with this property. That is, double a given number with k digits, you are to tell if the resulting number consists of only a permutation of the digits in the original number.

Input Specification:

Each input contains one test case. Each case contains one positive integer with no more than 20 digits.

Output Specification:

For each test case, first print in a line "Yes" if doubling the input number gives a number that consists of only a permutation of the digits in the original number, or "No" if not. Then in the next line, print the doubled number.

用例输入:

1234567899

输出

Yes

2469135798
细节注意点:1.输出No的时候也要输出数字;2.最高位进位要显示
#include<stdio.h>
#include<string.h>
int main()
{
  char num[21];
  gets(num);
  int a[10],b[10];
  for(int i=0;i<10;i++)
  {
    a[i]=b[i]=0;
  }
  int flag=1;
  for(int i=0;i<strlen(num);i++)
  {
    a[num[i]-'0']++;
  }
  char tmp[21];
  int jinwei=0;
  for(int i=strlen(num)-1;i>=0;i--)
  {
    tmp[i]=((num[i]-'0')*2+jinwei)%10+'0';
    if((num[i]-'0')*2>9)
    {
      jinwei=1;
    }
    else
    {
      jinwei=0;
    }
  }
  tmp[strlen(num)]=0;
  for(int i=0;i<strlen(num);i++)
  {
    b[tmp[i]-'0']++;
  }
  for(int i=0;i<10;i++)
  {
    if(a[i]!=b[i])
    {
      flag=0;
      break;
    }
  }
  if(flag==1)
  {
    printf("Yes\n");
    printf("%s",tmp);
  }
  else
  {
    printf("No\n");
    if(jinwei==1)
    {
      printf("1%s",tmp);
    }
    else
    {
      printf("%s",tmp);
    }
  }
  return 0;
}

猜你喜欢

转载自blog.csdn.net/bawangtu/article/details/81024675