判断一个数n是否是happy number。happy number的定义是,各位数依次平方求和,看是否能等于1,如果不等于1,再重复上述过程。实际上,这个过程将会是一个循环。[猜的,并没有证明]。
class Solution { public: map<int, bool>flag; bool isHappy(int n) { if (n == 1) { return true; } map<int, bool>::iterator it = flag.find(n); if (it != flag.end()) { return false; } else { flag.insert(map<int, bool>::value_type(n, true)); } int tmpNum = 0; while (n > 0) { tmpNum += (n % 10) * (n % 10); n /= 10; } return isHappy(tmpNum); } };