Int and long long int


  • 1
    A

    This is my solution which gave wrong answer on input 2147395599.

      class Solution {
        public:
            int mySqrt(int x) {
               if(x==1||x==2||x==3){
        		return 1;
                }
                int high,low,mid;
                long long int temp;
                low=1;
                high=x;
                int ans=0;
                while(low<high){
                    mid=low+(high-low)/2;
                    temp=mid*mid;
                    if(temp<=x){
                        low=mid+1;
                        ans=mid;
                    }
                    else{
                        high=mid;
                    }
                    
                } 
                return ans;
            }
        };
    

    But When i changed low,mid,high to long long int it got accepted. How?

    class Solution {
            public:
                int mySqrt(int x) {
                   if(x==1||x==2||x==3){
            		return 1;
                    }
                    long long int high,low,mid,temp;
                    low=1;
                    high=x;
                    int ans=0;
                    while(low<high){
                        mid=low+(high-low)/2;
                        temp=mid*mid;
                        if(temp<=x){
                            low=mid+1;
                            ans=mid;
                        }
                        else{
                            high=mid;
                        }
                        
                    } 
                    return ans;
                }
            };

  • 0
    Y

    temp=mid*mid;

    if mid is int type ,mid * mid will also become int,so temp will be assign an int value which will become smaller than x for sure.So the loop goes on until it reaches x and ans will become x-1;

    so at least mid should be long long int type for this question.


Log in to reply
 

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