【问题标题】:how to understand happy number from leetcode如何从 leetcode 中理解快乐数
【发布时间】:2015-06-07 19:24:54
【问题描述】:

这是来自 leetcode 的问题: 编写一个算法来确定一个数字是否“快乐”。 快乐数字是由以下过程定义的数字:从任何正整数开始,将数字替换为其数字的平方和,然后重复该过程直到数字等于 1(它将保持不变),或者循环在一个不包括 1 的循环中无限循环。这个过程以 1 结束的那些数字是快乐数字。

Example: 19 is a happy number    

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

问题1:根据我的理解,如果发生1,则返回True,否则它将无限运行我从这句话中理解的循环“或者它在不包括1的循环中无限循环。” 但是,在我从互联网上找到了这个问题的一些答案后,我发现我的理解是错误的。应该是如果 1 发生返回 True,** 并且如果任何数字在集合中重复,则结束循环并返回 False。 **好吧,老实说,问题是“或者它在一个不包括 1 的循环中无限循环。”为什么我们只是让程序在它所说的循环中无休止地运行??

问题2:对于第二个问题,我认为是关于理解代码。这是我从internet找到的:

def isHappy(n):
    stop = {1}
    while n not in stop:
        stop.add(n)
        n = sum(int(d)**2 for d in str(n))
    return n == 1

从这段代码中,我可以理解,如果发生 1,它将停止运行 while 循环并返回 True。但是,如果在集合中发生重复数字,我认为它也会停止运行 while 循环并返回 True,因为下一行后跟while语句仍然是return n==1。但是,实际上它会输出False。例如 由于 89 在集合中再次重复,输出 False。 抱歉我的冗长描述。简单地说,我的问题是这个错误是如何出现的?在编码中,没有明确返回False的地方

【问题讨论】:

  • n == 1 评估结果是什么?
  • 我明白了!!@Hurkyl n 如果 = 为 1,则返回 true,否则返回 false!非常感谢!

标签: python


【解决方案1】:

你发布的isHappy函数是正确的。

这就是它的工作原理 -

  1. 它将计算数字的平方并将其保存在n中。
  2. 如果 n 为 1,则停止。否则,它会将 n 附加到更改列表和循环中。但只要 n 是更改列表中的任何数字,循环就会中断。
  3. 在 Python 中,当控制退出循环时,它会将最后的值存储在变量中。因此,n 存储了最后一次计算。
  4. 现在,如果 n 为 1,则 n == 1 返回 True,否则返回 False。

希望对您有所帮助。

【讨论】:

  • 您为什么需要set替换为list
  • 在存储非重复数字方面,List 比 Set 有什么优势?
  • 哎呀对不起,我困了,把它当作字典。现已修复。
【解决方案2】:

我就是这样做的,虽然有点乱

    #Python program to check if a number is a happy number

    #Creating an user defined function which returns True if the number is happy else False
    def happy(num) :

        #Creating a copy of the number in a string and a iterating point
        copy = str(num)
        square = num

        #Proceeding with while loop due to unknown iterations
        while True : #inifinte loop
    
            square = sum(int(j) ** 2 for j in list(str(square))) #Sum of the number's digit squares
    
            if square == 1:
                test = True
                break
    
            elif square == 4:
                test = False
                break
    
        return test

    check = int(input('Enter the number: '))
    print('The number {} {} a happy number'.format(check, ('is') if happy(check) == True else ('is not')))
    
    

【讨论】:

    【解决方案3】:

    以下是快乐数字问题的流行解决方案。这个关键是每个数字的平方和都没有出现过,否则会死循环。

    class Solution:
        # @param {integer} n
        # @return {boolean}
        def isHappy(self, n):
            s=set()
            while n!=1 and n not in s:
                s.add(n)
                n= sum([int(x)**2 for x in str(n)])
            return n==1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-19
      • 2020-05-01
      • 2021-06-27
      • 1970-01-01
      相关资源
      最近更新 更多