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;       
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值