题目链接:http://www.patest.cn/contests/pat-a-practise/1023

题目:

1023. Have Fun with Numbers (20)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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 file 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

分析:

给你一个数(大数),推断其*2的结果数是否和原数是一样的排列,注意这里不是说给出的数都是1-9的排列。仅仅是题目中举样例用到了1-9而已。

这里设置了ans[]数组。对于原数的每一个数都++。对于结果数的每一个数都--,那么最后仅仅要推断ans是否全都0就能够推断原数和结果数是否是同样的排列

注意:

考虑到进位,乘以2以后可能会多出一位。并且20位的数字要用string表示而不是用long long表示。

能够看到下面数字的表示范围中long long不够20位。

int ,long , long long类型的范围

unsigned int 0~4294967295
int 2147483648~2147483647
unsigned long 0~4294967295
long 2147483648~2147483647
long long的最大值:9223372036854775807 (刚好19位)
long long的最小值:-9223372036854775808
unsigned long long的最大值:18446744073709551615
__int64的最大值:9223372036854775807
__int64的最小值:-9223372036854775808
unsigned __int64的最大值:18446744073709551615

AC代码:

#include<stdio.h>
using namespace std;
int ans[10];
char num1[22];
char num2[22];
int main(void){
 //freopen("F://Temp/input.txt", "r", stdin);
 while (scanf("%s", num1) != EOF){
  for (int k = 0; k< 10; k++){
   ans[k] = 0;
  }
  int di = 0, jin = 0,ji = 0;
  int i;
  for (i = 21; num1[i] == 0; i--);//找到最后一位的下标開始计算
  for ( ; i >= 0; i -- ){
   ji = (num1[i] - '0') * 2;
   ans[num1[i] - '0'] ++;//ans对原数对应位的个数++
   di = ji % 10;//*2后的当前位的数字
   num2[i] = di + jin + '0';
   ans[num2[i] - '0'] --;//ans对结果数的对应位的个数--
   jin = (ji + jin) / 10;
  }
  if (jin != 0)ans[jin] ++;
  for (i = 1; i < 10; i++){
   if (ans[i] != 0)break;
  }//推断ans是否所有都为0。若是,则说明原数和结果数是同样的排列
  if (i == 10){
   puts("Yes");
  }
  else {
   puts("No");
  }
  if (jin != 0)printf("%d", jin);
  puts(num2);
 }
 return 0;
}


截图:


——Apie陈小旭

posted on 2017-07-17 17:35  lxjshuju  阅读(781)  评论(0编辑  收藏  举报