Clean Java Solution


  • 0
    A
    public int integerReplacement(int n) {
    	int count = 0;
    	while (n != 1) {
    		if ((n & 1) == 0)
    			n = n >>> 1;
    		else
    			n = bitCount(n + 1) > bitCount(n - 1) || n == 3 ? n - 1 : n + 1;
    		count++;
    	}
    	return count;
    }
    
    int bitCount(int n) {
    	return n == 0 ? 0 : (n & 1) + bitCount(n >>> 1);
    }

Log in to reply
 

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