What's wrong with my Binary Search?

  • 0

    The algorithm is same with top discussion, but it ends up with time limit exceeded. Can anyone tell me why?

    class Solution {
        public int mySqrt(int x) {
            if(x==0) return 0;
            int max = 1;
            while(max*max<x) max=2*max;
            if (max*max==x) return max;
            int val = max/2;
            int i = max;
            while(! (i*i<=x && (i+1)*(i+1)>x) ){
                if(i*i>x) i -= val;
                else i += val;
                val = val / 2;
            return i;

Log in to reply

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