I have found 4 is endless


  • -1
    B
    bool isHappy(int n){
        int o = n;
        while(n != 1){
            if(n == 4) break;//back to nonendless
            //printf("%d\n" , n);
            int tmp = 0;
            while(n){
                tmp += (n % 10) * (n % 10);
                n /= 10;
            }
            n = tmp;
            if (o == tmp) break;//back to self
        }
        return n == 1;
    }
    

  • -1
    A

    then it should return false


  • 0

    @bigtomato Your code doesn't compile. (got fixed)


  • 0
    B

    @ManuelP
    I am so sorry about it , code should be :

    bool isHappy(int n){
        int o = n;
        while(n != 1){
            if(n == 4) break;//back to nonendless
            //printf("%d\n" , n);
            int tmp = 0;
            while(n){
                tmp += (n % 10) * (n % 10);
                n /= 10;
            }
            n = tmp;
            if (o == tmp) break;//back to self
        }
        return n == 1;
    }
    

Log in to reply
 

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