202. Happy Number

1.描述

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

2.分析

3.代碼

int squares(int n) {
    int sum = 0;
    while (n > 0) {
        sum += (n % 10) * (n % 10);
        n /= 10;
    }
    return sum;
}

bool isHappy(int n) {
    if (n <= 0) return false;
    
    int fast = n;
    int slow = n;
    for (;;) {
        fast = squares(squares(fast));
        slow = squares(slow);
        if (1 == fast || 1 == slow) return true;
        if (fast == slow) break;
    }
    return false;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 文/路雨飛飛 一 站在風中 站在雨里 站在燦爛的陽光里 站在巔峰 站在深谷 站在每一步腳印里 站在傷口 站在痛中 ...
    路雨飛飛閱讀 248評論 2 6
  • 本周抽空去杭州的華泰證券營業部開通了分級基金權限,一位陽光帥氣的工作人員熱情地遞上他的名片,滿臉笑意地告訴我,“我...
    sharespeak閱讀 181評論 0 2
  • 今天上午老師講了第四章this和base的用法,還有運算符重載,自定義轉換。自定義轉換真是沒聽懂,下午做了兩個作業...
    蘆繼超閱讀 106評論 0 0
  • 如果今天,你依然雙手放在身后,邁著超外八卻相當爺們的步伐,笑嘻嘻的對我說,老x啊,叫一盤糖醋魚回來給你吃吧,還是要...
    熱拿鐵和無糖閱讀 297評論 1 2
  • 2016-10-29 樊登讀書會中山分會 圖文來自國家地理雜志 我也想對所有心懷夢想的人說:我今年50歲,十年前開...
    樊登讀書會中山分會閱讀 254評論 1 1