标签:
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
C解法
bool isHappy(int n) { int lastOne = 0, nextNum = 0; if(n == 1) return true; else if(n == 0 || n == 2 || n == 3 || n == 4) //之所以把4放进去是因为后来发现所有的回归都是回归到4的 return false; else { while(n) { lastOne = n % 10; nextNum += lastOne * lastOne; n = n / 10; } return isHappy(nextNum); //树的后遗症,一直递归 }
C++解法:
class Solution { public: bool isHappy(int n) { int lastNum = 0, getNum = 0; if(n == 1) return true; else if(n == 0 || n == 2 || n == 3) return false; else { unordered_set<int> ln; //建立一个set来保存遇到过的值 while(true) { ln.insert(n); getNum = 0; while(n > 0) { lastNum = n % 10; getNum += lastNum * lastNum; n /= 10; } if (getNum == 1) return true; else if (ln.find(getNum) != ln.end()) //如果在set中发现之前出现过,说明循环了,返回0 return false; n = getNum; } } } };
标签:
原文地址:http://www.cnblogs.com/dylqt/p/4884335.html