Solution with Java


  • -1
    I

    public boolean isHappy(int n) {

        int result = n;
        
        while(result > 10){
            result = 0;
            while(n > 0){
                int i = n % 10;
                n = n/10;
                result += Math.pow(i,2);
            }
            n = result;
            
        } //this while loop calculates the input number and make it to a number less than and equal to 10
    

    // The happy numbers less than and equal to 10 are 1,7,10

        if(n == 7) return true;
        if(n == 10) return true;
        if(result == 1) return true;
        
        return false;
    }

  • 0
    P

    why somebody will vote down a Discuss when it is absolutely not bad? isn't it hurt someone?


  • -1
    Y

    public class Solution {
    public boolean isHappy(int n) {
    if (n==1) {
    return true;
    }
    if (n==2||n==3) {
    return false;
    }
    int temp = n;
    int a = 1;
    while(a!=n){
    temp = happy(temp);
    if (temp == 1) {
    return true;
    }
    if (a == temp) {
    return false;
    }
    if (temp/10==0) {
    a = temp;
    }
    }
    return false;
    }
    public int happy(int n) {
    int sum = 0;
    int temp = sum * sum;
    while(n/10!=0){
    temp = n%10;
    sum += temptemp;
    n = n/10;
    }
    return sum+n
    n;
    }
    }


Log in to reply
 

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