Find the rule yourself with permutation.


  • 1

    Based on one assumption that following happy number rule, you can always reduce it to one digit number regardless of in the middle or at final stage.

    So we can permute from 1..9, and

    public boolean isHappy(int n) {
    		if (n < 0) n = -n;
    		
    		while (n > 9) {
    			int tmp = 0;
    			while (n > 0) {
    			    int rm = n % 10;
    				tmp += rm * rm;
    				n /= 10;
    			}
    			n = tmp;
    		}
            
    		switch (n) {
    			case 1:
    			case 7: return true;
    			default: return false;
    		}
    	
        }
    

Log in to reply
 

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