Is 3 a happy number?


  • 0
    M

    According to my logic and also manually tracking, 3 should be a happy number. But Leet OJ is says false. Can anyone tell me why?

    public class Solution {
        public boolean isHappy(int n) {
            int sum=0;
            Set<Integer> s = new HashSet<Integer>(); 
            s.add(new Integer(n));
            while (n!=1) {
                while (n>=1) {
                    sum = sum + (n%10*n%10);
                    n = n/10;
                }
                if (s.contains(new Integer(sum))) {
                    return false;
                }
                s.add(new Integer(sum));
                n = sum;
                sum = 0;
            }
            return true;
        }
    }

  • 1
    Y

    It seems that your code is a little problematic.
    I rewrote your code again and get the result that 3 is not a happy number actually.
    Maybe your calculation is wrong.
    Here is my code:

    public class Solution{
    public boolean isHappy(int n){
    	int sum = 0;
    	Set<Integer> s = new HashSet <Integer>();
    	//s.add(new Integer(n)); // the first input n should not be put in the hashset
    	while (n != 1){
    		while (n >= 10){
                //if the condition is n>=1; then your code will go into dead loop for number that are not happy number
    			sum = sum + ((n%10) * (n%10));
    			n = n / 10;
    			System.out.println("first"+n);
    		}
    		sum = sum + n * n;
    		System.out.println("second"+sum);
    		if(s.contains(sum)){
    			System.out.println("not a happy number");
    			return false;
    		}
    		else{
    			s.add(sum);
    		}
    		n = sum;
    		sum = 0;
    	}
    	System.out.println("is a happy number");
    	return true;
    }
    

    }


  • 1
    D

    3
    9
    81
    65
    61
    37
    58
    89
    145
    42
    20
    4
    16
    37 (second time 37, start loop now)

    So it is not


Log in to reply
 

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