TLE when using bit shift instead of divide


  • 0
    R

    For find sqrt(x) question using binary search

    public class Solution {
        public int mySqrt(int x) {
            if(x <= 1) return x;
            int left = 1, right = x;
            while(left < right) {
                int mid = left + (right - left) /2;   /*this line*/
                if(mid <= x / mid) {
                    left = mid + 1;
                } 
                else right = mid;
            }
            return left - 1;
        }
    }
    

    if I write the expression for mid as mid=low+(high-low)>>1; i get TLE, isn't bit shift supposed to be faster? I usually use (low+high)>>1 instead of (low+high)/2 in binary search questions, is that less efficient?


  • 0

    The + is evaluated before the >>. Add parentheses.

    Next time please also tell which input case you failed.


  • 0
    R

    parenthesis worked thank you it was a Operator priority issue thank you. Previous it was failing at "6"


Log in to reply
 

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