算法作业HW20 202. Happy Number

来源:互联网 发布:淘宝男质量好的店铺 编辑:程序博客网 时间:2024/04/24 16:44

Description:


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.


 

Note:

Example: 19 is a happy number

  • 12 + 92 = 82
  • 82 + 22 = 68
  • 62 + 82 = 100
  • 12 + 02 + 02 = 1

Solution:

  Analysis and Thinking:

题目要求循环计算每位数字的平方和,知道出现结果为1时返回True,或者重复返回False

 

  Steps:

1.定义平方和辅助函数,获得其模10以及除10的结果,将其相乘与前一记录和值相加,直到n除10结果为0

2.定义map用于记录过程,计算输入数字饿平方和

3.当平方和不为1,查找在record对应下标是否为true,若是,重复了,返回false

4.若不是,置其为true

5.最后表示没有重复,且到了平方和为1,返回true

 

Codes:

class Solution {public:    bool isHappyNum(int x) {        unordered_map<int, bool> record;        int sum = helper_Sum(x);        while(sum != 1)        {            if(record[sum] == true)                return false;            record[sum] = true;            sum = helper_Sum(sum);        }        return true;    }    int helper_Sum(int n)    {        int result = 0;        while(n)        {            int temp = n%10;            n /= 10;            result = result+(temp*digit);        }        return result;    }};

Results: