LeetCode-202. 쾌락수-C 언어

7403 단어 LeetCode
bool ishappy(int n, int *cnt)
{
    (*cnt)++;/* cnt to control the depth of callstack, max is 40 */
    if((*cnt) >= 40) {
        return false;
    }
    if(n == 1) return true;
    int tmp=0;

    while(n) {
        tmp += (n%10) * (n%10);
        n /= 10;
    }
    return ishappy(tmp, cnt);    
}
bool isHappy(int n){
    int cnt = 0;
    return ishappy(n, &cnt);
}

/* way2 */
bool isHappy(int n) {
    int tmp;
    int tmp2;
    int ret=0;
    int arr[50];
    int index=0;
    int i;
    ret = n; 
    
    do {
        tmp = ret;
        ret = 0;
        while(tmp) {
            ret += ((tmp%10)*(tmp%10));
            tmp /= 10;
        }
        
        for(i=0; i<index; i++){
            if(arr[i] == ret){
                return false;
            }
        }
        arr[index++] = ret;
        
    }while(ret > 1);
    return true;
}

좋은 웹페이지 즐겨찾기