国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

202. Happy Number

2019-11-08 02:19:52
字體:
來源:轉載
供稿:網友

題目

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 Credits: Special thanks to @mithmatt and @ts for adding this problem and creating all test cases.

Subscribe to see which companies asked this question.


思路

循環求happyNum,退出條件是為1返回true,數字重復形成循環則返回false


代碼

class Solution {public: int getHappyNum(int num) { int result = 0; while(num) { result += pow(num%10,2); num /= 10; } return result; } bool isHappy(int n) { if(n <= 0) { return false; } vector<int> numFlag; numFlag.push_back(n); while(n) { n = getHappyNum(n); if(n == 1) { return true; } //形成循環了 if(find(numFlag.begin(),numFlag.end(),n) != numFlag.end()) { return false; } numFlag.push_back(n); } return false; }};
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 根河市| 前郭尔| 林口县| 黄浦区| 玉溪市| 大英县| 丹巴县| 外汇| 磐安县| 西华县| 旬邑县| 嘉定区| 延吉市| 全州县| 米易县| 鄢陵县| 仪陇县| 阿尔山市| 临西县| 静乐县| 新巴尔虎左旗| 东乡族自治县| 龙南县| 含山县| 五台县| 新邵县| 桐城市| 双牌县| 商都县| 广宁县| 屯留县| 满洲里市| 巴东县| 江口县| 和平县| 宜兰市| 白河县| 合川市| 维西| 祁连县| 长子县|