Help! why the following code is wrong


  • 0
    W
    double myPow(double x, int n) 
    	{
            double result=0;
    	    bool flag=1;
            if(abs(x-0.0)<0.0000001&&n<0)
    		return 0;
    	    if(n<0)
    	    {
    			flag=0;
    			n=-1*n;
    	    }
    	    result=res(x,n);
    	    if(flag==0)
                 result=1.0/result;
    	    return result;
        }
    
    double res(double x,int n)
    	{
    		double result;
    			if(n==0)
    				return 1;
    			else
    				if(n==1)
    					return x;
    
    			if(n%2==1)
    			{
    				result= res(x,n>>1);
    				result=result*result*x;
    				return result;
    			}
    			else
    				if(n%2==0)
    				{
    						result= res(x,n>>1);
    						result=result*result;
    						return result;
    				}
    	}
    

    this answer is right.but following answer is wrong when n=2,I want to know why.

    double res(double x,int n)
        	{
        		double result;
        			if(n==0)
        				return 1;
        			else
        				if(n==1)
        					return x;
        
        			if(n&0x1==1)
        			{
        				result= res(x,n>>1);
        				result=result*result*x;
        				return result;
        			}
        			else
        				if(n&0x1==0)
        				{
        						result= res(x,n>>1);
        						result=result*result;
        						return result;
        				}
        	}

Log in to reply
 

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