BFS C++ solution


  • 0
    P

    long long is for the case INT_MAX + 1 overflow

    class Solution {
    public:
        int integerReplacement(int n) {
            int res = 0;
            queue<long long> q;
            q.push(n);
            while(!q.empty()){
                int n = q.size();
                for(int i = 0; i < n; i++){
                    long long x = q.front();
                    q.pop();
                    if(x == 1) return res;
                    if(x % 2 == 0) q.push(x / 2);
                    else{
                        q.push(x + 1);
                        q.push(x - 1);
                    }
                }
                res++;
            }
            return res;
        }
    };
    

Log in to reply
 

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