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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 文/路雨飞飞 一 站在风中 站在雨里 站在灿烂的阳光里 站在巅峰 站在深谷 站在每一步脚印里 站在伤口 站在痛中 ...
    路雨飞飞阅读 243评论 2 6
  • 本周抽空去杭州的华泰证券营业部开通了分级基金权限,一位阳光帅气的工作人员热情地递上他的名片,满脸笑意地告诉我,“我...
    sharespeak阅读 180评论 0 2
  • 今天上午老师讲了第四章this和base的用法,还有运算符重载,自定义转换。自定义转换真是没听懂,下午做了两个作业...
    芦继超阅读 105评论 0 0
  • 如果今天,你依然双手放在身后,迈着超外八却相当爷们的步伐,笑嘻嘻的对我说,老x啊,叫一盘糖醋鱼回来给你吃吧,还是要...
    热拿铁和无糖阅读 297评论 1 2
  • 2016-10-29 樊登读书会中山分会 图文来自国家地理杂志 我也想对所有心怀梦想的人说:我今年50岁,十年前开...
    樊登读书会中山分会阅读 254评论 1 1