Four different solutions in C, all accepted as best, well-commented


  • 1
    //https://www.kidscodecs.com/happy-numbers/
    int isHappy(int n)
    {
        int sum = 0;
        for(; n; n/=10)
            sum += (n%10)*(n%10);
        if(sum == 1)
            return true;
        int arr[] = {4, 16, 37, 58, 89, 145, 42, 20};
        for(int i = 0; i < sizeof(arr)/sizeof(int); i++)
            if(sum == arr[i])
                return false;
        return isHappy(sum);
    }
    

    int squareSum(int n)
    {
        int sum=0, t;
        while(n)
        {
            t = n%10;
            sum += t*t;
            n /= 10;
        }
        return sum;
    }
    
    //AC - 0ms - there must be a loop here - since the squareSum is finite while the loop is infinite;
    int isHappy(int n)
    {
        int slow=n, fast=n;
        do
        {
            slow = squareSum(slow);
            fast = squareSum(fast);
            fast = squareSum(fast);
        } while(slow != fast);
        if(slow == 1) return 1;
        else return 0;
    }
    

    int squareSum(int n)
    {
        int sum=0, t;
        while(n)
        {
            t = n%10;
            sum += t*t;
            n /= 10;
        }
        return sum;
    }
    
    int isHappy(int n)
    {
        int slow=n, fast=n;
        while(slow > 1)
        {
            slow = squareSum(slow);
            if(slow == 1) return true;
            fast = squareSum(squareSum(fast));
            if(fast == 1) return true;
            if(slow == fast) return false;
        }
        return true;
    }
    

    //only 1 and 7 in [0, 9] is happy number, and since there must a loop and each number will be equivalent to [0, 9];
    int isHappy(int n)
    {
        while(n > 6)
        {
            int next = 0;
            while(n)
            {
                next += (n%10)*(n%10);
                n /= 10;
            }
            n = next;
        }
        return n == 1;
    }

Log in to reply
 

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