Accepted but too complicated? could have written it in a cleaner way


  • 0
    A
    public class Solution {
        public int mySqrt(int x) {
            int a=0;
            int b=x;
            int s=x;
            if (x<=0){return x;}
            while (b!=a){
                if (x-Math.pow(s,2)==0){
                    return s;
                }
                else if (x-Math.pow(s,2)>0){
                    if ((s+b)/2-s==0){return s;}
                    else{
                       a=s; 
                       s=(a+b)/2;
                    }
                }
                else{
                    if ((s+a)/2-a==0){return a;}
                    else{
                        b=s; 
                        s=(a+b)/2;
                    }
                }
            }
            return s;
        }
    }

Log in to reply
 

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