7-1 Happy Numbers (20 分)
A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits in base-ten, and repeat the process until the number either equals 1 (where it will stay), or it loops endlessly in a cycle that does not include 1. Those numbers for which this process ends in 1 are happy numbers and the number of iterations is called the degree of happiness, while those that do not end in 1 are unhappy numbers (or sad numbers). (Quoted from Wikipedia)
For example, 19 is happy since we obtain 82 after the first iteration, 68 after the second iteration, 100 after the third iteration, and finally 1. Hence the degree of happiness of 19 is 4.On the other hand, 29 is sad since we obtain 85, 89, 145, 42, 20, 4, 16, 37, 58, and back to 89, then fall into an endless loop. In this case, 89 is the first loop number for 29.
Now your job is to tell if any given number is happy or not.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤100). Then N lines follow, each contains a positive integer (no more than 10
4 ) to be tested.
Output Specification:
For each given number, output in a line its degree of happiness if it is happy, or the first loop number if it is sad.
Sample Input:
3
19
29
1
Sample Output:
4
89
0
分析:简单数学运算
注意点:
1、(1,10,100)的输出分别为(0,1,1)。直接把1当特例输出。
2、输入的数也要计入loop判断,如89.
#include <iostream>
#include <cmath>
#include <set>
using namespace std;
int sum(int a){
int ans = 0;
while(a!=0){
int d = a%10;
ans += (d*d);
a/=10;
}
return ans;
}
set<int> mem;
int main() {
int n,num;
cin>>n;
for(int i=0;i<n;i++){
cin>>num;
if(num==1){
cout<<"0"<<endl;
continue;
}
mem.clear();
int ans = sum(num),count = 1;
bool flag = false;
mem.insert(ans);
mem.insert(num);
while(ans!=1){
count++;
ans = sum(ans);
if(mem.find(ans)!=mem.end()){
flag = true;
break;
}
mem.insert(ans);
}
if(flag) cout<<ans<<endl;
else cout<<count<<endl;
}
return 0;
}