Will this O(1) space solution always work?


  • 0
    M

    This is my solution using python:

    class Solution:
    # @param {integer} n
    # @return {boolean}
    def isHappy(self, n):
        if n<10:
            return n==1 or n==7
        newNum=0
        while n>0:
            newNum+=pow(n%10,2)
            n/=10
        return self.isHappy(newNum)
    

    It passes all the test cases, but I am wondering if this is a "right" solution.

    The point is can we prove the square for each digits sum up to a number less than 10 always?


  • 0
    D

    Not sure about this. It indeed passed all the tests. Another concern is whether next integer calculated will surely be some integer already calculated. Also how about integer overflow?

    These all need mathematical conduction.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.