PAT甲级 1023. Have Fun with Numbers (20) 大整数运算(利用字符串进行模拟)

参考链接:https://www.liuchuo.net/archives/2151
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

题目大意:给出一个长度不超过20的整数,问这个整数两倍后的数位是否为原数位的一个排列。不管是yes还是no最后都要输出整数乘以2的结果。因为长度不超过20,以经远远超过整形的存储长度,所以要用字符串进行!
分析:使用string存储这个数,没个数的数位乘以2 + 进位,同时设立arr来标记数位出现的情况。只有最后book的每个元素都是0的时候才说明这两个数字是相等的一个排列结果~~~

#include<iostream>
#include<string.h>
using namespace std;

int main(){
	
	string num;
	cin>>num;
	int arr[10] = {0};
	int flag = 0;//代表进位的数 
	for(int i=num.size()-1;i>=0;i--){//注意右边是数字最低位,往左依次是高位 
		int temp = num[i]-'0';
		arr[temp]++;
		temp = temp * 2 + flag;
		flag = 0;//加完进位后记得清0 
		if(temp >= 10){
			temp = temp - 10;
			flag = 1;//向高位进1 
		}
		num[i] = temp + '0';
		arr[temp]--;
	} 
	
	int flag2 = 0;
	for(int i=0;i<10;i++){
		if(arr[i]!=0){
			flag2 = 1;
			break;
		}	
	}
	
	if(flag == 0 && flag2 == 0)//当没有进位时,并且两倍数的各位数出现次数一样 
		cout<<"Yes"<<endl;
	else 
		cout<<"No"<<endl;
	if(flag == 1)//当最高位进位时,新的最高位就是1 
		num = '1' + num;	
	for(int i=0;i<num.size();i++)
		cout<<num[i]; 
	
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/qq_29762941/article/details/81606479