LeetCode 30天挑戰 Day-2

LeetCode 30 days Challenge - Day 2

本系列將對LeetCode新推出的30天算法挑戰進行總結記錄,旨在記錄學習成果、方便未來查閱,同時望爲廣大網友提供幫助。


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:

Input: 19
Output: true
Explanation: 
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1

題目要求分析:給定一個整數,將該整數每一位平方加和得到新的整數,重複直到整數爲1或出現循環。

解法:

快慢指針:遇到出現循環情況的題目,可以考慮快慢指針的方法:

  • 快指針:一次走2步(在本題中即進行兩次運算)。
  • 慢指針:一次走1步(進行一次運算)。

在若干次迭代後,如果存在循環,快慢指針會指向同一值,此時退出循環即可。


Solution

class Solution {
public:
    int get_pow(int n) {
        int tmp = 0;
        while (n) {
            tmp += (n % 10) * (n % 10);
            n /= 10;
        }
        return tmp;
    }
    bool isHappy(int n) {
        if (n == 1) return true;
        int slow = n, fast = n;
        do {
            slow = get_pow(slow);
            fast = get_pow(fast);
            fast = get_pow(fast);
        } while (slow != fast);
        return (slow == 1);
    }
};

傳送門:Happy Number

2020/4 Karl

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章