202. Happy Number

给定一个数,得到这个数的数位上的数字的平方和,然后循环,如果最后能等于1,则输出true,否则为false.

难点:不知道这个数到底要循环多少轮才能得到1.
思路:设置一个最大的循环数(如:20轮),如果达到最大循环次数,还不等于1,则返回false.

#include<iostream>
#include<math.h>
#include<string>
using namespace std;
bool isHappy(int n) {
    string s = to_string(n);
    int ans = 0, count = 0;
    while (count < 20) {
        for (int i = 0; i < s.length(); i++) {
            ans += pow(int(s[i] - '0'), 2);
        }
        if (ans == 1) {
            return true;
        }
        count += 1;
        s = to_string(ans);
        ans = 0;
    }
    return false;
}
int main() {
    cout << isHappy(0) << endl;
    return 0;
}
原文地址:https://www.cnblogs.com/luo-c/p/12865964.html