Happy Number

题目来源
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

1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1

判断一个整数是不是快乐的…最直接的方法就是直接算…用了一个哈希表来存储已经出现过的,假如出现循环节了的话那肯定就不是快乐数了!

class Solution {
public:
    bool isHappy(int n) {
        unordered_map<int, int> map;
        while (n != 1 && !map[n]) {
            map[n]++;
            int newN = 0;
            while (n > 0) {
                newN += (n % 10) * (n % 10);
                n /= 10;
            }
            n = newN;
        }
        if (n == 1)
            return true;
        else
            return false;
    }
};

我们用了O(n)的空间,然后又有大神出现了,大吼一声说,渣渣,Floyd你都忘了吗?要你何用!咔嚓,把我干掉了!
实际上也挺简单的,就是设置一个快指针一个慢指针,然后假如有环的话,快指针会追上慢指针,假如没环的话,就到尾巴了,这道题目中的尾巴就是1。

class Solution {
public:
    bool isHappy(int n) {
        int fast = n, slow = n;
        do {
            slow = digitSqualSum(slow);
            fast = digitSqualSum(fast);
            fast = digitSqualSum(fast);
        } while (fast != slow && fast != 1);
        if (fast == 1)
            return true;
        else
            return false;
    }
    
    int digitSqualSum(int n)
    {
        int newN = 0;
        while (n > 0) {
            newN += (n % 10) * (n % 10);
            n /= 10;
        }
        return newN;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,998评论 0 23
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,788评论 0 33
  • 别闲着啦, 赶紧买房结婚, 不然要交 “单身税”啦! 1 这一周我和闺蜜、女性朋友们聊的最多的话题就是: 看了产妇...
    蜕变的痛阅读 313评论 0 1
  • 今日带妈去协和看病,挂了骨科钱文伟副教授的号,民航医院诊断是类风湿性关节炎,好不容易轮到我们进去,我妈主动描述病情...
    一世惊鸿阅读 121评论 0 0
  • 我不知道鸟往哪里飞, 也不知道风往哪里追, 这样的夜晚太美又太黑, 却只是徒增伤悲。
    梅丽得斯阅读 254评论 0 1