1023 Have Fun with Numbers (20)(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.
輸入格式:
Each input file contains one test case. Each case contains one positive integer with no more than 20 digits.輸出格式:
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.
題目大意:
這道題目主要是判斷是否一個數字在乘以2之後,他的結果是否仍然爲原來數字的組合,比如說
22*2=44,顯然,原來的數字是2個2的組合,而結果是2個4的組合,不一樣,因此輸出No。
解題方法:
這道題目在解題上沒有難度,直接把輸入的數字用char數組存儲,然後從數組的末尾開始,做乘法,不過需要考慮進位的問題,具體可以看我代碼。
易錯點:
1. 不要漏了最後一個進位,如999只用for循環會漏掉1998中的1
程序:
#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[])
{
char num[21];
int douNum[22], check[10] = {0};
int douIdx = 0, res, add = 0, flag = 0;
scanf("%s",num); /* 輸入測試樣例 */
for (int i = strlen(num) - 1; i >= 0; i--)
{
res = (num[i]-'0') * 2 + add;
if (res >= 10)
{
res %= 10;
add = 1; /* 進位置1 */
}
else
add = 0; /* 進位置0 */
douNum[douIdx++] = res;
}
if (add == 1) /* 如果有36進位比如(9->18) */
douNum[douIdx++] = 1;
for (int i = 0; i < douIdx; i++)
check[douNum[i]]++; /* 對應數字出現次數+1 */
for (int i = 0; i < strlen(num); i++)
check[num[i]-'0']--; /* 對應數字剩餘出現次數-1 */
for (int i = 0; i < 10; i++)
if (check[i] != 0) /* 如果出現該數字出現次數不相同 */
{
flag = 1;
break;
}
if (flag == 1)
printf("No\n");
else
printf("Yes\n");
for (int i = douIdx-1; i >= 0; i--)
printf("%d", douNum[i]);
return 0;
}
如果對您有幫助,幫忙點個小拇指唄~