#include <iostream>#include <stdio.h>#include <vector>#include <string>#include <unordered_map>using namespace std;/*问题: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 number12 + 92 = 8282 + 22 = 6862 + 82 = 10012 + 02 + 02 = 1分析:一个快乐的数被定义为将这个数的各个位上的数字拆分后的平方和到最后变成1,即可。如果陷入某个死循环(?如何判断)就说明不是快乐的数。问题的难点在于如何判定陷入了死循环。可以设置一个访问标记数组,如果当前数已经在之前出现过了,则必定是重复的。要得到1,最终肯定某一位上要有1个1,其余低位为0,要么为1,10,100,1000等而拆分后的各个位数的和要为1,10,100,1000,......而每一位1:12:43:94:165:256:367:498:649:81能变成1,10,100,...的右1+9,1+49,81+9,33,得到1818,得到6565,得到6161,得到3737,得到5858,得到8989,得到145145,得到4242,得到2020,得到44,得到1616,得到3737,得到58,58已经出现过,死循环,输入:1933输出:truefalse关键:1 问题的难点在于如何判定陷入了死循环。可以设置一个访问标记数组,如果当前数已经在之前出现过了,则必定是重复的。*/class Solution {public: //将一个数的每一位拆分,得到每一位的结果在平方 int sum(int num) { vector<int> nums; //123,12 do{ int value = num % 10; nums.push_back(value); num /= 10; }while(num > 0); int result = 0; if(nums.empty()) { return result; } int size = nums.size(); for(int i = 0 ; i < size ; i++) { result += ( nums.at(i) * nums.at(i) ); } return result; } bool isHappy(int n) { unordered_map<int , bool> visited; //当前数没有访问过 int num; bool isFind = false; while(visited.find(n) == visited.end()) { if(1 == n) { isFind = true; break; } visited[n] = true; num = sum(n); n = num; } if(isFind) { return true; } else { return false; } }};void print(vector<int>& result){ if(result.empty()) { cout << "no result" << endl; return; } int size = result.size(); for(int i = 0 ; i < size ; i++) { cout << result.at(i) << " " ; } cout << endl;}void process(){ int num; Solution solution; while(cin >> num ) { bool answer = solution.isHappy(num); if(answer) { cout << "true" << endl; } else { cout << "false" << endl; } }}int main(int argc , char* argv[]){ process(); getchar(); return 0;}
新闻热点
疑难解答