国产探花免费观看_亚洲丰满少妇自慰呻吟_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; }};
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 如皋市| 女性| 化州市| 肥城市| 赞皇县| 玉溪市| 松江区| 宁远县| 江口县| 吴桥县| 延寿县| 宜阳县| 荔波县| 琼海市| 佛坪县| 温泉县| 疏附县| 巴彦县| 汉中市| 永兴县| 延庆县| 米易县| 石狮市| 阿荣旗| 日喀则市| 靖边县| 白沙| 邵武市| 扬州市| 清流县| 常山县| 泰宁县| 镇赉县| 望奎县| 平度市| 崇义县| 古田县| 龙川县| 新闻| 安庆市| 古丈县|