Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9f72047

Browse files
committed
添加 0202.快乐数.md Scala版本
1 parent 78c6602 commit 9f72047

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

‎problems/0202.快乐数.md‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -385,5 +385,38 @@ bool isHappy(int n){
385385
return bHappy;
386386
}
387387
```
388+
Scala:
389+
```scala
390+
object Solution {
391+
// 引入mutable
392+
import scala.collection.mutable
393+
def isHappy(n: Int): Boolean = {
394+
// 存放每次计算后的结果
395+
val set: mutable.HashSet[Int] = new mutable.HashSet[Int]()
396+
var tmp = n // 因为形参是不可变量,所以需要找到一个临时变量
397+
// 开始进入循环
398+
while (true) {
399+
val sum = getSum(tmp) // 获取这个数每个值的平方和
400+
if (sum == 1) return true // 如果最终等于 1,则返回true
401+
// 如果set里面已经有这个值了,说明进入无限循环,可以返回false,否则添加这个值到set
402+
if (set.contains(sum)) return false
403+
else set.add(sum)
404+
tmp = sum
405+
}
406+
// 最终需要返回值,直接返回个false
407+
false
408+
}
409+
410+
def getSum(n: Int): Int = {
411+
var sum = 0
412+
var tmp = n
413+
while (tmp != 0) {
414+
sum += (tmp % 10) * (tmp % 10)
415+
tmp = tmp / 10
416+
}
417+
sum
418+
}
419+
}
420+
```
388421
-----------------------
389422
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /