# Happy Number

## Desicription

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:

```Input: 19
Output: true
Explanation:
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 02 = 1```

## Solution

```class Solution {
private:
int fun(int n) {
int sum = 0;
while(n) {
sum += (n%10) * (n%10);
n /= 10;
}
return sum;
}
public:
bool isHappy(int n) {
int slow = n;
int fast = n;
do {
slow = fun(slow);
fast = fun(fast);
fast = fun(fast);
} while(fast != slow);
if(slow == 1)
return true;
else
return false;
}
};```

0 条评论

• ### Leetcode 202 Happy Number

Write an algorithm to determine if a number is "happy". A happy number is a nu...

• ### leetcode 202 Happy Number

Write an algorithm to determine if a number is "happy".

• ### LeetCode 202: 快乐数 Happy Number

一个 “快乐数” 定义为：对于一个正整数，每一次将该数替换为它每个位置上的数字的平方和，然后重复这个过程直到这个数变为 1，也可能是无限循环但始终变不到 1。如...

• ### 【LeetCode 202】 关关的刷题日记35 – Leetcode 202. Happy Number

关关的刷题日记35 – Leetcode 202. Happy Number 题目 Write an algorithm to determine if a n...

• ### LeetCode202 Happy Number

Write an algorithm to determine if a number is “happy”.

• ### Q202 Happy Number

Write an algorithm to determine if a number is "happy". A happy number is a numb...

• ### C#版(打败97.89%的提交) - Leetcode 202. 快乐数 - 题解

Leetcode 202.Happy Number 在线提交: https://leetcode-cn.com/problems/happy-number/...

• ### 752. Open the Lock

思路： 实际上每一位有10种变化情况，总共有4位，所以有4104^{10}种状态，初始从”0000”开始衍变，到target的最短路径可以用BFS来表达。当...

• ### 大数据工程师（开发）面试题(附答案)

MapReduce 1. 不指定语言，写一个WordCount的MapReduce 我：最近刚学了scala，并且就有scala版本的WordCount，刚好学...

• ### Python3刷题系列（四）

https://leetcode.com/problems/happy-number/

• ### Golang Leetcode 202. Happy Number.go

版权声明：原创勿转 https://blog.csdn.net/anakinsun/article/details/89012332

• ### 浙江大学计算机与软件学院2019年保研上机模拟练习

A happy number is defined by the following process: Starting with any positive i...

• ### LeetCode 752：打开转盘锁 Open the Lock

你有一个带有四个圆形拨轮的转盘锁。每个拨轮都有10个数字：'0', '1', '2', '3', '4', '5', '6', '7', '8', '9' 。每...

• ### python笔记53-Leetcode面试题

Leetcode上有个练习题，也是面试经常会遇到的：请实现一个函数，把字符串 s 中的每个空格替换成”%20”

• ### Day2-1 leetcode202Happy number

Write an algorithm to determine if a number n is “happy”.

• ### Leetcode Palindrome Number

Determine whether an integer is a palindrome. An integer is a palindrome when it...

### Reck Zhang

TencentGame Developer

Tencent · Game Developer (已认证)