C++ Easy Solution using binary search

  • 2
    // Remember to use INT64 to avoid overflow.
    bool isBadVersion(int version);
    class Solution {
        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;
                    ans = (int)mid;
                    r = mid - 1;
                    l = mid + 1;
            return ans;

  • 0

    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

    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.