Leetcode算法学习日志-202 Happy Number

来源:互联网 发布:华为软件开发招聘 编辑:程序博客网 时间:2024/05/20 18:03

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