Topic
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 and replace the number by the Sum of the squares of its digits, and repeat the process until the number equals 1 (where it would stay), or it loops Endl essly in a cycle which does not include 1. Those numbers for which this process ends in 1 is happy numbers.
Example:19 is a happy number
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
Ideas
No
Code
/* ---------------------------------------------------------* Date: 2015-04-22* sjf0115* title: 202.Happy number* Website: https://leetcode.com/problems/happy-number/* Result: ac* Source: leetcode* Blog:------------------------------------------------------------* *#include <iostream>#include <vector>#include <algorithm>using namespace STD;classSolution { Public:BOOLIshappy (intN) {if(n = =1){return true; }//if if(n = =0){return false; }//if returnRecursion (n); }Private: vector<int>visited;BOOLRecursion (intN) {if(n = =1){return true; }//if intnum = n;intTmp,value =0; while(num) {tmp = num%Ten; Value + = TMP * TMP; Num/=Ten; }//while //Determine if a ring is formed vector<int>:: Iterator result = Find (Visited.begin (), Visited.end (), value);if(Result! = Visited.end ()) {return false; }//ifVisited.push_back (value);returnrecursion (value); }};intMain () {solution solution;intn =2;if(Solution.ishappy (n)) {cout<<n<<"is Happy number"<<endl; }//if Else{cout<<n<<" is not Happy number"<<endl; }return 0;}
Run time
[Leetcode]202.happy number