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
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2= 1

樸素的解法。用快慢指針來標(biāo)記環(huán)路。

#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
    bool isHappy(int n) {
        int slow = solve_num(n);
        int fast = solve_num(slow);
        if (slow == 1)
            return true;
        while (slow != fast) {
            slow = solve_num(slow);
            if (slow == 1)
                return true;
            fast = solve_num(fast);
            fast = solve_num(fast);
        }
        return false;
    }

    int solve_num(int n) {
        int bw = 0;
        int sum = 0;
        while (n != 0) {
            bw = n % 10;
            sum += bw * bw;
            n /= 10;
        }
        return sum;
    }

};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,134評(píng)論 0 23
  • 文/青山若夫 -1- 每到一處旅行,我總愛到當(dāng)?shù)氐臅旯涔?。在互網(wǎng)絡(luò)的沖擊下,實(shí)體書店日漸式微,傳統(tǒng)閱讀也陷入重圍...
    青山若夫閱讀 2,196評(píng)論 40 76
  • 萬萬姥姥閱讀 203評(píng)論 0 0
  • 夏天的燥熱滲透在每個(gè)人的心里,高中生活的結(jié)束,讓所有人都有說不清道不明的感受。 畢業(yè)晚宴那天,林婉瑤精心打扮了一番...
    兔子說得對(duì)閱讀 595評(píng)論 0 0
  • 有一種遠(yuǎn)方叫流浪,有一種思念叫鄉(xiāng)愁。 ――題記 我是大山里的孩子,內(nèi)心純凈而明亮。我時(shí)常帶著弟弟爬上最高的山,望著...
    七七丫頭1閱讀 392評(píng)論 2 1

友情鏈接更多精彩內(nèi)容