202. Happy Number
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.
使用set即可,注意這道題最終輸出要麼是因為1結束,要麼是由於出現環路結束。注意set返回的是pair,所以要判斷set的第二個元素。
class Solution {
public:
bool isHappy(int n) {
if(n <= 0)
return 0;
set<int> s;
while((s.insert(n)).second){
int b = 0;
while(n != 0){
int a = n % 10;
b += a * a;
n /= 10;
}
if(b == 1)
return true;
else
n = b;
}
return false;
}
};
相關文章
- Leetcode 202 Happy Number Javascript 解決方案LeetCodeAPPJavaScript
- Happy coding ! lol?APP
- Check if String is HappyAPP
- 十一黃金週放假通知--HappyAPP
- 洛谷 P11323 Happy CardAPP
- No need to add that my being happy in Forks is an impossibility.APP
- 2019PHP 面試彙總(code happy)PHP面試APP
- Linguistics-English-Happy Labor Day September 2, 2024NGUIAPP
- Furion分表分庫我也要happy codingAPP
- JavaScript Number()JavaScript
- 關於軟體測試領域的 Happy PathAPP
- Kata:Hamming number
- JavaScript Number toLocaleString()JavaScript
- JavaScript Number toString()JavaScript
- Number.NaNNaN
- JavaScript Number 物件JavaScript物件
- Leetcode Number of islandsLeetCode
- Spark雙流join-延遲資料--double_happySparkAPP
- Perfect Number 完美數
- [LeetCode] Third Maximum NumberLeetCode
- [LeetCode] Find the Duplicate NumberLeetCode
- Leetcode 9 Palindrome NumberLeetCode
- Number.parseInt() 方法
- Number.parseFloat()方法
- Number.isSafeInteger()方法
- Number.isNaN()方法NaN
- Number.isFinite()方法
- Js中的NumberJS
- Number.POSITIVE_INFINITY
- Number.ATIVE_INFINITY
- Big Number hd 1212
- 7.104 ITERATION_NUMBER
- Leetcode 447 Number of BoomerangsLeetCodeOOM
- react input[type='number']React
- number(p,s)(轉)
- Last digit of a huge numberASTGit
- 136. Single Number
- Serial number lookup for Panasonic
- D. The Number of Imposters