[LeetCode By Go 66]202. Happy Number

題目

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: 19 is a happy number

12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

解題思路

建立一個(gè)map numMap,用于存放每次計(jì)算出的新值
每次計(jì)算一個(gè)新值后,判斷該值是否為1,如果是1,則返回true
如果不是1,則判斷該值在map中是否存在,如果存在,則返回false
否則將新值放入map中

代碼

func getNewNum(num int) (newNum int) {
    for ; num > 0 ; {
        a := num % 10
        num = num / 10
        newNum += a * a
    }

    return newNum
}
func isHappy(n int) bool {
    var numMap map[int]bool
    numMap = make(map[int]bool)
    var newNum int
    newNum = n

    for {
        if 1 == newNum {
            return true
        }
        newNum = getNewNum(newNum)

        _, ok := numMap[newNum]
        if ok {
            return false
        } else {
            numMap[newNum] = true
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問(wèn)題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,891評(píng)論 0 33
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,018評(píng)論 0 23
  • 2017年3月22日是改變我觀念的日子,是讓我找回自信的日子,這一天讓我懂得了該如何把握自己的人生,與此同時(shí)真心的...
    模具配件鄭鵬閱讀 673評(píng)論 0 4
  • 多少次,我坐在電腦前敲擊鍵盤的時(shí)候,總有個(gè)聲音悄悄傳來(lái),它在我耳邊輕輕回響:該寫了,怎么還不寫呢? 是的,確實(shí)應(yīng)該...
    蘭桂騰芳閱讀 1,998評(píng)論 6 10

友情鏈接更多精彩內(nèi)容