先看看題目:
202. Happy Number
Easy

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

Return True if n is a happy number, and False if not.

Example: 

Input: 19
Output: true
Explanation: 
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

附上通關證明:

截圖 2020-08-19 下午3.26.17

 

 

我的想法:題目是說把數字拆成個位數,然後各自平方相加,如果出現結果是 1 的話就回傳true,如果重複的話就回傳 false,這題我就依照題目需求寫一個function,然後把結果存在map中,如果出現重複就結束迴圈,粗略寫了一下,意外拿到100%。

class Solution {
      fun isHappy(n: Int): Boolean {
         fun getNextNumber(n:Int):Int{
            var result = 0
            for(c in n.toString()){
                val cInt = Character.getNumericValue(c)
                val cN = if(cInt!=0) (cInt*cInt) else 0
                result += cN
            }
            return result
        }
        val map = HashMap<Int,Boolean>()
        var nextN = n
        while(map[nextN]==null){
            map[nextN] = true
            nextN = getNextNumber(nextN)
            if(nextN==1)
                return true
        }
        return false
    }
}
arrow
arrow
    全站熱搜

    Deyu 發表在 痞客邦 留言(0) 人氣()