Newcomer, my 2ms c ugly code.


  • 1
    L
    #include <stdio.h>
    #include <string.h>
    #define MAX 1000
    char cache[MAX];
    char initilized=0;
    int calc(int n) {
        int r=0;
        while(n>0) {
            r+= (n%10)*(n%10);
            n /= 10;
        }
        return r;
    }
    bool isHappy(int n) {
        char r;
        if(initilized==0){
            initilized=1;
            memset(cache, 0xff, sizeof(cache));
            cache[1]=1;
        }
        if(n >= MAX)n=calc(n);
        if(cache[n] == 2) return 0;
        if(cache[n] != -1)return cache[n];
        cache[n] = 2;
        r = isHappy(calc(n));
        cache[n] = r;
        return r;
    }

Log in to reply
 

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