My easy-understanding cpp code


  • 0
    C
    // Forward declaration of isBadVersion API.
    bool isBadVersion(int version);
    
    class Solution {
    public:
        int firstBadVersion(int n) 
        {
            if(n == 1) return 1;
            
            int start_idx = 1, end_idx = n;
            
            while(start_idx < end_idx)
            {
                // !!!!!!!! avoid overflow ///////////////////
                int mid = start_idx + (end_idx - start_idx)/2;
                if( isBadVersion(mid) ) end_idx = mid;
                else                    start_idx = mid+1;
            }
            
            return start_idx;
        }
    };

Log in to reply
 

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