2ms Java solution


  • 2
    H

    It can be proven that loop goes only with numbers under 243. Because numbers bigger than 243 can only produce a smaller number than itself. I used 8 integers (256 bits) to store whether a number has already occurred.

    public boolean isHappy(int n) {
    	int[] mark = new int[8];
    	while (n > 1) {
    		n = convert(n);
    		if (n < 243) {
    			int sec = n >> 5;
    			int mask = 1 << (n & 0x1f);
    			if ((mark[sec] & mask) > 0) {
    				return false;
    			}
    			mark[sec] |= mask;
    		}
    	}
    	return true;
    }
    
    private int convert(int n) {
    	int sum = 0;
    	while (n > 0) {
    		int t = n % 10;
    		sum += t * t;
    		n /= 10;
    	}
    	return sum;
    }

  • 0
    J

    nice job! I use the hashtable ... so lazy I am


Log in to reply
 

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