算法作业HW20 202. Happy Number

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:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值