202. Happy Number

来源:互联网 发布:计算圆周率的算法 编辑:程序博客网 时间:2024/06/06 05:45

202. Happy Number

Write an algorithm to determine if a number is “happy”.

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.

Example:
19 is a happy number

1*1 + 9*9 = 82
8*8 + 2*2 = 68
6*6 + 8*8 = 100
1*1 + 0*0 + 0*0 = 1

Analysis:
这个博客写的很好:《[LeetCode] Happy Number 快乐数》http://www.cnblogs.com/grandyang/p/4447233.html

Source Code(C++):

#include <iostream>#include <algorithm>#include <vector>using namespace std;class Solution {public:    bool isHappy(int n) {        if (n<1) {            return false;        }        else {            vector<int> v;            v.push_back(n);            while(n != 1) {                             int sum = 0;                while(n>0) {                    sum += (n%10)*(n%10);                    n /= 10;                }                n=sum;                              if (find(begin(v), end(v), n) != end(v)) {   //之前出现过这个数,则进入无限循环                    return false;                }                v.push_back(n);            }            return true;        }    }};int main() {    Solution sol;    cout << sol.isHappy(11);    return 0;}
0 0