Leetcode算法學習日誌-202 Happy Number

Leetcode 202 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

  • 12 + 92 = 82
  • 82 + 22 = 68
  • 62 + 82 = 100
  • 12 + 02 + 02 = 1

題意分析

對一個數的各位求平方和,得到的數繼續上述操作,如果能得到1(得到1後再進行平方和操作值不再變化)就爲快樂數,不然就返回false。

解法分析

對於任何a0000形式的數,經過平方和後的數一定小於他本身,因此對於n>100的數,平方和g(n)<n,也就是說對於一個數進行各位平方和,得到的結果一定有上界,假設該數不是一個快樂數,則該平方和操作次數無限,對於有限的上界和無限的操作次數,這一定會導致數的重複出現,當第一次出現一個之前出現過的數時,循環便會開始,注意這裏的循環不一定包含了前面出現的所有數,這可能只是個局部循環,本題最直接的方法就是建立一個set,將出現的數放入set,如果出現重複的數,表明循環已經產生,然而並沒有停留在1,因此這是一個非快樂數,如果出現1,當然直接返回true。本題還可以利用雙指針,一個快指針一個慢指針,慢指針每次進行一步平方和,快指針進行兩次,如果是快樂數,則快指針必然首先到1,然後停住,最後被慢指針追上,此時慢指針也是1,如果不是快樂數,則會進入循環(可能是包含部分數的小循環),則快指針一定能追上慢指針,此時雖然和前面一樣,快指針等於慢指針,但他們的值不等於1.C++代碼如下:

class Solution {
public:
    int squareSum(int n){
        int res=0;
        while(n){//this is important
            res+=(int)pow(double(n%10),2);
            n/=10;
            cout<<n%10<<endl;
        }
        return res;
    }
    bool isHappy(int n) {
        int fast=n,slow=n;
        do{
            slow=squareSum(slow);
            //cout<<slow;
            fast=squareSum(fast);
            fast=squareSum(fast);
        }while(fast!=slow);//there are two cases,one is fast catches up with slow,the other
            //one is fast stay at 1,and slow catches up with fast.
        if(slow==1)
            return true;
        return false;       
    }
};



發佈了79 篇原創文章 · 獲贊 16 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章