Why the following code flows?


  • 0
    J

    It works fine when I define mid as long long. Any clue? Thanks!

       class Solution {
        public:
            int mySqrt(int x) {
                assert(x>=0);
                if(x==0 || x==1) return x;
                int lo = 1;
                int hi = x/2+1;
                while(lo<=hi){
                    int mid = lo+(hi-lo)/2;
                    long long t = mid*mid;
                    if(t==x) return mid;
                    else if(t>x) hi=mid-1;
                    else lo=mid+1;
                }
                return hi;
            }
        };

Log in to reply
 

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