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 104)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
代码如下:
#include <iostream>
#include <cmath>
#include <set>
using namespace std;
int main()
{
int n;
string num;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> num;
set<int> rec;
rec.insert(stoi(num)); // 需要注意这里也要把初始数字插入进去,因为循环有可能会回到初始数据
bool flag = true;
int cnt = 0;
while (true)
{
if (num == "1")
break;
int temp = 0;
for (int j = 0; j < num.size(); j++)
{
temp += pow(num[j] - '0', 2);
}
cnt++;
if (rec.find(temp) == rec.end())
{
rec.insert(temp);
num = to_string(temp);
}
else
{
cout << temp << endl;
flag = false;
break;
}
}
if (flag)
cout << cnt << endl;
}
return 0;
}
7-2 Zigzag Sequence (25 分)
is time your job is to output a sequence of N positive integers in a zigzag format with width M in non-decreasing order. A zigzag format is to fill in the first row with M numbers from left to right, then the second row from right to left, and so on and so forth. For example, a zigzag format with width 5 for numbers 1 to 13 is the following:
1 2 3 4 5
10 9 8 7 6
11
算法解析:快乐数、锯齿序列、AVL树与人气排名

这篇博客探讨了四种计算机科学算法问题:快乐数的判断,锯齿序列的生成,AVL树的平衡性检查以及朋友圈中的人气排名。通过示例代码详细解释了每种算法的实现过程和逻辑,帮助读者理解这些概念并解决相关问题。
最低0.47元/天 解锁文章
499

被折叠的 条评论
为什么被折叠?



