From 485f6a806a712356fb3112b8522149650bc2756c Mon Sep 17 00:00:00 2001 From: nolanzzz Date: Thu, 2 Sep 2021 23:49:37 -0400 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200202.=E5=BF=AB=E4=B9=90?= =?UTF-8?q?=E6=95=B0=20PHP=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0202.快乐数.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/problems/0202.快乐数.md b/problems/0202.快乐数.md index e6365c71..710c824d 100644 --- a/problems/0202.快乐数.md +++ b/problems/0202.快乐数.md @@ -223,6 +223,37 @@ func isHappy(_ n: Int) -> Bool { } ``` +PHP: +```php +class Solution { + /** + * @param Integer $n + * @return Boolean + */ + function isHappy($n) { + // use a set to record sum + // whenever there is a duplicated, stop + // == 1 return true, else false + $table = []; + while ($n != 1 && !isset($table[$n])) { + $table[$n] = 1; + $n = self::getNextN($n); + } + return $n == 1; + } + + function getNextN(int $n) { + $res = 0; + while ($n > 0) { + $temp = $n % 10; + $res += $temp * $temp; + $n = floor($n / 10); + } + return $res; + } +} +``` + ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321)