A binary search solution in C


  • 0
    G
    // Forward declaration of isBadVersion API.
    bool isBadVersion(int version);
    
    class Solution {
    public:
    	int firstBadVersion(int n) 
    	{
    		if (!isBadVersion(n)) return 0;
    		int s = 1;
    		int e = n-1;
    		int r = n;
    		while (s <= e)
    		{
    			int m = ((long long)s + (long long)e) / 2;;
    			if (isBadVersion(m))
    			{
    				r = m;
    				e = m - 1;
    			}
    			else
    			{
    				s = m + 1;
    			}
    		}
    
    		return r;
    	}
    };

Log in to reply
 

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