---
# System prepended metadata

title: LeetCode 202. Happy Number
tags: [Leetcode]

---

---
title: 'LeetCode 202. Happy Number'
disqus: hackmd
---

# LeetCode 202. Happy Number



## Description

Write an algorithm to determine if a number n 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.

* 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.

Return true if n is a happy number, and false if not.

## Example

Input: n = 19
Output: true
Explanation:
1^2^ + 9^2^ = 82
8^2^ + 2^2^ = 68
6^2^ + 8^2^ = 100
1^2^ + 0^2^ + 0^2^ = 1
## Constraints

1 <= n <= 2^31^ - 1

## Answer

方法1
此題可用一個個位數慢慢取出來算平方相加，若為1就跳出return trye，若為4就return false，因為4是有重複值出現的話一定會遇到的值。所以只要有4就表示數值一定重複。


```Cin=
//2021_11_24
bool isHappy(int n) {
    if(n == 1){return true;}
    int temp = 0, ans = 0;
    while(n != 1){
        ans = 0;
        while(n != 0){
            temp = n % 10;
            ans += (temp*temp);
            n /= 10;
        }
        n = ans;
        if(n == 4){return false;}
    }
    return true;
}
```
方法2
因為若不是happy number的話，他循環計算的結果都會落在2~6之間，所以只要n為6以上才要繼續算，若不是就判斷其是不是happy number。
```Cin=
bool isHappy(int n) {
    int tmp = 0, new = 0;
    while(n>6){
        new = 0;
        while(n){
           tmp = n%10;
            new += tmp*tmp;
            n /= 10; 
        }
        n = new;
    }
    return n == 1;
}
```
說明：http://en.wikipedia.org/wiki/Happy_number#Sequence_behavior

## Link
https://leetcode.com/problems/happy-number/
###### tags: `Leetcode` 
