My solution with Java


  • -1
    A
    public class Solution {
    	
    	public static int calc(int n)
    	{
    		int res = 0, temp = 0;
    		while (n/10 != 0)
    		{	
    			res += Math.pow((n%10),2);
    			n/=10;
    		}
    		res += Math.pow((n%10),2);
    		return res;
    	}
    	public static boolean isHappy(int n)
    	{
    		ArrayList<Integer> array = new ArrayList<Integer>();
    		int result = n;
    		while (result != 1)
    		{
    			result = calc(result);
    	        //System.out.println(result);
    			if (array.contains(result)) return false;
    			array.add(result);
    		}
    		return true;
    	}
        
    }
    

    its better with hashSet like belowing said。


  • 2
    S

    Isn't ArrayList lookup linear in time? with HashSet you could do constant time.


  • 0
    A

    true。thank you。


Log in to reply
 

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