Swift solution


  • 0
    class Solution {
        func integerReplacement(_ n: Int) -> Int {
            var n = n
            var count = 0
            
            while n != 1 {
                if n & 1 == 0 {
                    n >>= 1
                } else if n == 3 || ((n >> 1) & 1) == 0 {
                    n -= 1
                } else {
                    n += 1
                }
                count += 1
            }
            
            return count
        }
    }
    

Log in to reply
 

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