朋友數使用set解決

朋友數

如果兩個整數各位數字的和是一樣的,則被稱爲是“朋友數”,而那個公共的和就是它們的“朋友證號”。例如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 <cstdio>
#include <cstring>
#include <set>
#include <iostream>
#include <algorithm>
using namespace std;
int n, sum;
set<int> arr;
int num(int n){
    int sum;
    while(n){
        sum+=n%10;
        n/=10;  
    }
    return sum;
}
int main()
{
    cin >> n;
    for (int i = 0; i < n; i++){
        int j;
        cin >> j;
        arr.insert(num(j));
    }
    cout << arr.size() << endl;
    for (set<int>::iterator i = arr.begin(); i != arr.end(); ++i){
        if (i == arr.begin()) printf("%d", *i);
        else printf(" %d", *i);
    }
    return 0;
}
發佈了29 篇原創文章 · 獲贊 19 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章