1. 程式人生 > >PAT乙級 1064 朋友數 (20 分)

PAT乙級 1064 朋友數 (20 分)

如果兩個整數各位數字的和是一樣的,則被稱為是“朋友數”,而那個公共的和就是它們的“朋友證號”。例如 123 和 51 就是朋友數,因為 1+2+3 = 5+1 = 6,而 6 就是它們的朋友證號。給定一些整數,要求你統計一下它們中有多少個不同的朋友證號。

輸入格式:

輸入第一行給出正整數 N。隨後一行給出 N 個正整數,數字間以空格分隔。題目保證所有數字小於 104

輸出格式:

首先第一行輸出給定數字中不同的朋友證號的個數;隨後一行按遞增順序輸出這些朋友證號,數字間隔一個空格,且行末不得有多餘空格。

輸入樣例:

8
123 899 51 998 27 33 36 12

輸出樣例:

4
3 6 9 26

程式碼:

#include<stdio.h>
#include<string.h>
int main(){
	int N;
	scanf("%d",&N);
	int number,id[37]={0},cnt=0,sign=1;
	char temp[5];
	for(int i=0;i<N;++i){
		int sum=0;
		scanf("%d",&number);
		sprintf(temp,"%d",number);//數字轉字串
		for(int j=0;j<strlen(temp);++j){
			sum+=temp[j]-'0';
		}
		if(id[sum]==0){
			++cnt;
			id[sum]=1;
		}
	}
	printf("%d\n",cnt);
	for(int i=1;i<=37;++i){
		if(id[i]==1){
			if(sign){
				sign=0;
				printf("%d",i);
			}
			else{
				printf(" %d",i);
			}
		}
	}
} 

在這裡插入圖片描述