I. Title Description
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
1^2 + 9^2 = 82 (sum of squares of each bit)
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
Two. Topic analysis
The title asks for any positive integer, the sum of squares of the numbers on each digit, and if the result converges to 1 after several operations, the number is happy number, and the numbers are not happy numbers, which begin to loop from a number after many operations . We only use the rule to calculate the problem, and use a map to store the numbers that have already appeared, so that after each round of calculations to find the map, if the found value already exists, prove to have been in the loop, can jump out of the loop and determine that the integer is not happy number.
For more information on Happy number, refer to: Http://baike.baidu.com/link?url=slZGeshN-Igmd4geJ7PZ9hPwk_ Pzgzk6qttvzh5tpuiqipy8qzamg6o9-5-x-eu2wgoquhnasb7alb2eceatpvj0c9-3daqpjy0cpvmvp7ab3iiky6vu1qb8fhcbj_ eg1nt4ba9fdzzt1bzbqcsl5a
Three. Sample code
#include <iostream>#include <map>using namespace STD;classsolution{ Public:BOOLIshappy (intN) {if(N <0)return false;if(n = =1)return true; map<int, bool>Shownum; while(true) {inttemp =0; while(n) {temp + = (n%Ten) * (n%Ten); N/=Ten; }if(temp = =1)return true;Else if(Shownum[temp] = =true)//fall into circulation, sentenced to non-happy number return false;Else{Shownum[temp] =true; n = temp; } } }};
Some test results:
Four. Summary
No
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode Note: Happy number