解决问题的思路:
第一步:从上图中,我们可以发现:在闭区间[1,13]内的所有数经过次数有限的迭代后,它们将会变成1或者4,而1是happy number,4不是happy number。进而可以判断出闭区间[1,13]内的所有数的happy性。
第二步:下面我做了一个大胆的假设,所有的正数经过可接受的有限次迭代后都将变成1或者4。由于在数学上给出证明所需的时间远远大于用程序验证,所以暂且不进行数学证明,直接进行在线编程。结果正确。
代码如下:
class Solution {
public:
bool isHappy(int n) {
int quotient, remainder;
vector<int> digitalArr;
quotient = n;
int i = 1;
while(true) {
digitalArr.clear();
for(; quotient != 0; ) {
remainder = quotient % 10;
quotient = quotient / 10;
if(remainder != 0)
digitalArr.push_back(remainder);
}
quotient = 0;
for(vector<int>::iterator iter = digitalArr.begin(); iter != digitalArr.end(); iter++) {
quotient = quotient + (*iter) * (*iter);
}
if(quotient == 1 || quotient == 4)
break;
}
if(quotient == 1)
return true;
else
return false;
}
};
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文:http://blog.csdn.net/guanzhongshan/article/details/46785379