zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    uva 11997 K Smallest Sums
    uvalive 3135 Argus
    React-Redux填坑
    fetch方法
    react 学习前期用到的插件
    Redux:with React(一)
    Redux:data flow
    Redux:store
    Redux:Reducers
    Redux:action
  • 原文地址:https://www.cnblogs.com/luo-c/p/12865964.html
Copyright © 2011-2022 走看看