202. Happy Number
Write an algorithm to determine if a number n
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.
Return True if n
is a happy number, and False if not.
Example:
Input: 19 Output: true Explanation: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1
class Solution { public: //主要是判断平方和是否会重复,如果重复就会造成cycle,否则就可以一直算下去,直到为1 long help(int n){ long res = 0; while(n){ res += (n%10)*(n%10); n=n/10; } return res; } bool isHappy(int n) { if(n == 1){ return true; } if(m.find(n) != m.end()) return false; else{ m[n] = true; return isHappy(help(n)); } } private: map<int,bool> m; };
很巧妙,借鉴链表的快慢指针
class Solution { public: //借鉴链表是否有环的快慢指针法 long help(long n){ long res=0; while(n){ long tmp = n%10; n = n/10; res += tmp*tmp; } return res; } bool isHappy(int n) { long slow=n,fast=n; do{ slow = help(slow); fast = help(fast); fast = help(fast); if(slow == 1 || fast == 1) return true; }while(slow != fast); return false; } };