leetcode Happy Number

来源:互联网 发布:淘宝卖家使用尺码 编辑:程序博客网 时间:2024/06/03 16:39

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
解析:
 思路大概是,建立一个while循环,建立一个容器,保存每次的结果。
退出循环有两种情况:

1、每次插入结果前都判断容器是否包含了这个值,如果有的话就退出循环。
2、检查时还要判断结果是否为1,如果是的话也退出循环。
两者都不满足则一直循环。
在退出循环后判断是第一种情况退出的还是第二种情况,第一则返回false,第二则返回true。

代码:
class Solution {public:    bool isHappy(int n) {        // 保存数据的容器        vector<int> bottle;        int temp = getDigitsSum(n);        // 只要mp中不存在值且不为1就循环下去        while (find(bottle.begin(), bottle.end(), temp) == bottle.end() && temp != 1){            //插入temp值            bottle.push_back(temp);            temp = getDigitsSum(temp);        }        if (find(bottle.begin(), bottle.end(), temp) != bottle.end()){            return false;        }        if (temp == 1){            return true;        }    }    int getDigitsSum(int n){        int result = 0;        while (n >= 10){            result += pow(n%10, 2);            n = n/10;        }        // 直到n<10        result += pow(n, 2);        return result;    }};


0 0
原创粉丝点击