202. Happy Number

Problem

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

Input: 19
Output: true
Explanation: 
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

Code

static int var = [](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();
class Solution {
public:
    bool isHappy(int n) {
        vector<int> temp;
        while(1){
            temp.push_back(n);
            int res = 0;
            do{
                int remainder = n%10;
                res += remainder * remainder;
            }while((n/=10)!=0);
            if(res==1)
                return true;
            else if(find(temp.begin(),temp.end(),res)!=temp.end())
                return false;
            else
                n = res;
        }
    }
};

Result

202. Happy Number.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,151评论 0 10
  • The Inner Game of Tennis W Timothy Gallwey Jonathan Cape ...
    网事_79a3阅读 14,252评论 3 20
  • 感恩~坚持✊早起做早餐,用刚买的有机黄豆打处弄弄地豆浆,配上自己发明的馒头酸奶苹果派还有炒米饭,为孩子开启美好的一...
    毛毛细雨mmxy阅读 1,631评论 0 0
  • 记得小时候 最讨厌的便是写日记 那个时候 每天都是一样的 单纯和快乐 于是每天写日记成了最头疼的事情 直到有一天 ...
    房小虫阅读 1,105评论 0 0
  • Sublime Text 3非常实用,但是想要用好,一些快捷键不可或缺,所以转了这个快捷键汇总。 用惯了vim,有...
    入间阅读 1,534评论 0 2