自测-4 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.
Sample Input:
1234567899
Sample Output:
Yes
2469135798
算法思路:首先得看得懂英语。。。 题目意思是要我们输入一个有k位的数,看翻倍后的数是否由原来的数的数字只改变顺序构成。yes or no,然后输出翻倍后的值。
把问题分解。
首先要保存输入的数字。
因为数字太大,即使是long long位数也不够,所以要用字符来处理。然后将字符转化为数字,可用‘字符’-‘0’的方法。用一个整形数组保存。
将整形数组翻倍,用另一个数组保存。考虑进位。可能要拓展位数。
用两个数组来分别计算每个数字出现的次数,判断两个数组对应位置的数字是否相等。
如果翻倍后位数不同,可以直接判断不是,然后输出。
按要求输出。
程序如下:
#include <stdio.h>
#include <stdlib.h>
int input(int a[]); //将输入数字保存到数组a
void double_(int a[], int b[],int );//数字翻倍保存到数组b,如果位数变大,直接输出并退出。
void count(int a[], int b[],int c[],int d[],int );//用c和d计数a和b对应数字个数。
int compare(int c[], int d[]);//比较。
int main(){
int a[20], b[21], c[10] = {0}, d[10] = {0};
int digits;
digits = input(a);
double_(a, b, digits);
count(a, b, c, d, digits);
if(compare(c, d)){
printf("Yes\n");
}
else printf("No\n");
for (int i=0; i < digits; i++){
printf("%d", b[i]);
}
return 0;
}
int input(int *a){
char temp;
int i = 0;
temp = getchar();
while (temp >= '0' && temp <= '9'){
a[i] = temp - '0';
i++;
temp = getchar();
}
return i;
}
void double_(int *a, int *b, int n){
int carry = 0, i;
for (i = n-1; i>=0; i--){
b[i] = a[i] * 2 % 10;
if (carry){
b[i]++;
carry = 0;
}
if (a[i] * 2 >= 10){
carry = 1;
}
if (i == 0 && a[i]*2 >= 10){
for (int j = n; j>0; j--){
b[j] = b[j-1];
}
b[0]= 1;
printf("No\n");
for (i=0; i<=n; i++){
printf("%d", b[i]);
}
exit(0);
}
}
}
void count(int *a, int *b, int *c, int *d, int n){
int i;
for (i = 0; i<n; i++){
c[a[i]]++;
d[b[i]]++;
}
}
int compare(int *c, int *d){
int i, j = 1;
for (i=0; i<10; i++){
if (c[i] != d[i]){
j = 0;
break;
}
}
return j;
}