浙江大学 计算机与软件学院 2019年保研 上机 模拟练习 7-1 Happy Numbers (20 分)

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值