4ms Java solution


  • 2
    S
    public class Solution {
        public int integerReplacement(int n) {
            int i = 0;
    	long a = n;
    	while (a != 1){
    		if (a == 3) return i + 2;
    		if ((a & 1) == 0){
    			++i;
    			a = a >> 1;
    			continue;
    		}
    		if ((a & 2) == 2){
    			++a;
    			++i;
    		}
    		else{
    			--a;
    			++i;
    		}
    	}
    	return i;
        }
    }
    

    xxxxxxxxxx0 -> n = n / 2
    0000000011 -> n = n - 1
    xxxx1xxxx11 -> n = n + 1
    xxxxxxxxx01 -> n = n - 1
    In fact, I do not know why this is correct...


  • 0
    N
    This post is deleted!

Log in to reply
 

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