C++ Easy Solution using binary search


  • 2
    Y
    // Remember to use INT64 to avoid overflow.
    bool isBadVersion(int version);
    
    class Solution {
    public:
        int firstBadVersion(int n) {
            int ans = n;
            if(n < 2)
                return n;
            long long l = 1, r = n;
            while(l <= r){
                long long mid = (l + r)>>1;
                if(isBadVersion(mid)){
                    ans = (int)mid;
                    r = mid - 1;
                }else
                    l = mid + 1;
            }
            return ans;
        }
    };

  • 0
    K

    what prompted you to use long long int? My logic was right, but only after i changed my type to long long, was the solution accepted. Before that some garbage value was the o/p.


  • 0
    Y

    I think it is my experience that tells me to do so ... When we add two INT32, we should always be careful for the overflow.


Log in to reply
 

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