simple iterative C# solution


  • 0
    K
    public class Solution {
        public int IntegerReplacement(int n) {
            
            int i=0;
            ulong num = (ulong)n;
            while (num>1)
            {
                if (num%2==0)
                    num=num/2;
                else
                {
                    if (IsPowerOfTwo(num-1)) 
                        num = num-1;
                    else if (IsPowerOfTwo(num+1)) 
                        num = num+1;
                    else if (((num-1)/2)%2==0) 
                        num = num-1;
                    else 
                        num = num +1;
                }
                i++;
            }
            return i;
            
        }
        bool IsPowerOfTwo(ulong x)
        {
            return (x & (x - 1)) == 0;
        }
    }
    

Log in to reply
 

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